import { useState, useCallback } from 'react';
import { View, Text, FlatList, TouchableOpacity, ActivityIndicator, RefreshControl, ScrollView } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useQuery } from '@tanstack/react-query';
import { useFocusEffect, router } from 'expo-router';
import { api } from '../../../services/api';
import { useAuthStore } from '../../../stores/authStore';

const TYPE_LABEL: Record<string, string> = {
  SUSPEND_CLIENT:    'SUSPEND',
  REACTIVATE_CLIENT: 'REACTIVATE',
  ACTIVATE_CLIENT:   'ACTIVATE',
};
const TYPE_COLOR: Record<string, string> = {
  SUSPEND_CLIENT:    '#DC2626',
  REACTIVATE_CLIENT: '#059669',
  ACTIVATE_CLIENT:   '#0891B2',
};
const TYPE_BG: Record<string, string> = {
  SUSPEND_CLIENT:    '#FEE2E2',
  REACTIVATE_CLIENT: '#D1FAE5',
  ACTIVATE_CLIENT:   '#ECFEFF',
};
const STATUS_COLOR: Record<string, string> = {
  PENDING:   '#D97706',
  DONE:      '#059669',
  CANCELLED: '#6B7280',
};
const STATUS_BG: Record<string, string> = {
  PENDING:   '#FFFBEB',
  DONE:      '#D1FAE5',
  CANCELLED: '#F1F5F9',
};

const FILTERS = ['ALL', 'PENDING', 'DONE', 'CANCELLED'];

function formatDate(iso: string) {
  return new Date(iso).toLocaleDateString('en-PH', {
    month: 'short', day: 'numeric', year: 'numeric',
  });
}

export default function ManualTasksScreen() {
  const { user } = useAuthStore();
  const [filter, setFilter] = useState('ALL');
  const role = user?.roles?.[0] ?? user?.role ?? '';

  const queryParams = filter === 'ALL' ? '' : `?status=${filter}`;
  const { data, isLoading, refetch, isRefetching } = useQuery({
    queryKey: ['manual-tasks', filter],
    queryFn: () => api.get(`/api/v1/manual-tasks${queryParams}`).then(r => r.data?.data ?? r.data ?? []),
  });

  useFocusEffect(useCallback(() => { refetch(); }, [filter]));

  const tasks: any[] = data ?? [];

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: '#0891B2' }} edges={['top']}>
      <View style={{ flex: 1, backgroundColor: '#F8FAFC' }}>
        {/* Header */}
        <View style={{ backgroundColor: '#0891B2', paddingHorizontal: 20, paddingTop: 16, paddingBottom: 16, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-end' }}>
          <View>
            <Text style={{ color: '#FFF', fontSize: 28, fontWeight: '800' }}>Manual Tasks</Text>
            <Text style={{ color: '#A5F3FC', fontSize: 14, marginTop: 2 }}>{tasks.length} showing</Text>
          </View>
          {(role === 'ADMIN' || role === 'STAFF') && (
            <TouchableOpacity
              style={{ backgroundColor: 'rgba(255,255,255,0.2)', borderRadius: 12, paddingHorizontal: 16, paddingVertical: 10 }}
              onPress={() => router.push('/(app)/manual-tasks/new')}
              activeOpacity={0.7}
            >
              <Text style={{ color: '#FFF', fontWeight: '700', fontSize: 15 }}>+ New</Text>
            </TouchableOpacity>
          )}
        </View>

        {/* Filter chips */}
        <View style={{ backgroundColor: '#FFF', paddingHorizontal: 16, paddingVertical: 12, borderBottomWidth: 1, borderBottomColor: '#F1F5F9' }}>
          <ScrollView horizontal showsHorizontalScrollIndicator={false}>
            {FILTERS.map(f => {
              const isActive = filter === f;
              const color = f === 'ALL' ? '#0891B2' : STATUS_COLOR[f] ?? '#6B7280';
              return (
                <TouchableOpacity
                  key={f}
                  onPress={() => setFilter(f)}
                  style={{ borderRadius: 20, paddingHorizontal: 16, paddingVertical: 8, marginRight: 8, backgroundColor: isActive ? color : '#F1F5F9' }}
                  activeOpacity={0.7}
                >
                  <Text style={{ fontSize: 14, fontWeight: '700', color: isActive ? '#FFF' : '#64748B' }}>
                    {f === 'ALL' ? 'All' : f}
                  </Text>
                </TouchableOpacity>
              );
            })}
          </ScrollView>
        </View>

        {isLoading ? (
          <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <ActivityIndicator color="#0891B2" size="large" />
          </View>
        ) : (
          <FlatList
            data={tasks}
            keyExtractor={(item) => item.id}
            refreshControl={<RefreshControl refreshing={isRefetching} onRefresh={refetch} tintColor="#0891B2" />}
            contentContainerStyle={{ padding: 16, paddingBottom: 32 }}
            renderItem={({ item }) => {
              const typeColor = TYPE_COLOR[item.type] ?? '#6B7280';
              const typeBg    = TYPE_BG[item.type]    ?? '#F1F5F9';
              const typeLabel = TYPE_LABEL[item.type]  ?? item.type;
              const statusColor = STATUS_COLOR[item.status] ?? '#6B7280';
              const statusBg    = STATUS_BG[item.status]    ?? '#F1F5F9';
              const assignedName = item.assignedTo
                ? `${item.assignedTo.firstName} ${item.assignedTo.lastName}`
                : 'Unassigned';
              return (
                <TouchableOpacity
                  style={{ backgroundColor: '#FFF', borderRadius: 16, padding: 18, marginBottom: 12, borderWidth: 1, borderColor: '#F1F5F9', borderLeftWidth: 4, borderLeftColor: typeColor }}
                  onPress={() => router.push(`/(app)/manual-tasks/${item.id}`)}
                  activeOpacity={0.7}
                >
                  {/* Badges row */}
                  <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
                    <View style={{ borderRadius: 20, paddingHorizontal: 10, paddingVertical: 4, backgroundColor: typeBg }}>
                      <Text style={{ fontSize: 12, fontWeight: '700', color: typeColor }}>{typeLabel}</Text>
                    </View>
                    <View style={{ borderRadius: 20, paddingHorizontal: 10, paddingVertical: 4, backgroundColor: statusBg }}>
                      <Text style={{ fontSize: 12, fontWeight: '700', color: statusColor }}>{item.status}</Text>
                    </View>
                  </View>

                  {/* Client */}
                  {item.client && (
                    <Text style={{ fontSize: 17, fontWeight: '700', color: '#0F172A', marginBottom: 4 }}>
                      {item.client.firstName} {item.client.lastName}
                      <Text style={{ fontWeight: '400', color: '#64748B' }}> · {item.client.accountNumber}</Text>
                    </Text>
                  )}

                  {/* Assigned / Date */}
                  <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginTop: 4 }}>
                    <Text style={{ fontSize: 14, color: '#64748B' }}>{assignedName}</Text>
                    <Text style={{ fontSize: 13, color: '#94A3B8' }}>{item.createdAt ? formatDate(item.createdAt) : ''}</Text>
                  </View>

                  {/* Notes */}
                  {!!item.notes && (
                    <Text style={{ fontSize: 14, color: '#94A3B8', marginTop: 6 }} numberOfLines={2}>{item.notes}</Text>
                  )}
                </TouchableOpacity>
              );
            }}
            ListEmptyComponent={
              <View style={{ alignItems: 'center', paddingVertical: 60 }}>
                <Text style={{ fontSize: 17, color: '#94A3B8' }}>No manual tasks found</Text>
              </View>
            }
          />
        )}
      </View>
    </SafeAreaView>
  );
}
