import { View, Text, FlatList, TouchableOpacity, ActivityIndicator, RefreshControl } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useQueries } from '@tanstack/react-query';
import { router } from 'expo-router';
import { api } from '../../../services/api';

const STATUS_CONFIG: Record<string, { color: string; bg: string }> = {
  PENDING:   { color: '#92400E', bg: '#FEF3C7' },
  CONFIRMED: { color: '#166534', bg: '#DCFCE7' },
  DISPUTED:  { color: '#991B1B', bg: '#FEE2E2' },
};

export default function RemittancesScreen() {
  const [remittancesQ, unremittedQ] = useQueries({
    queries: [
      { queryKey: ['remittances'], queryFn: () => api.get('/api/v1/remittances?limit=50').then(r => r.data?.data ?? r.data) },
      { queryKey: ['unremitted'], queryFn: () => api.get('/api/v1/payments?unremitted=true').then(r => r.data).catch(() => null) },
    ],
  });

  const data = remittancesQ.data ?? [];
  const isLoading = remittancesQ.isLoading;
  const isRefetching = remittancesQ.isRefetching || unremittedQ.isRefetching;
  const refetchAll = () => { remittancesQ.refetch(); unremittedQ.refetch(); };

  // Compute unremitted total from raw payments or summary
  const unremittedPayments: any[] = Array.isArray(unremittedQ.data?.data)
    ? unremittedQ.data.data
    : Array.isArray(unremittedQ.data)
    ? unremittedQ.data
    : [];
  const unremittedTotal = unremittedQ.data?.totalUnremitted
    ?? unremittedPayments.reduce((s: number, p: any) => s + Number(p.amount ?? 0), 0);
  const unremittedCount = unremittedQ.data?.count ?? unremittedPayments.length;

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: '#0891B2' }} edges={['top']}>
      <View style={{ flex: 1, backgroundColor: '#F8FAFC' }}>
        {/* Header */}
        <View style={{ backgroundColor: '#0891B2', paddingHorizontal: 20, paddingTop: 12, paddingBottom: 20 }}>
          <TouchableOpacity onPress={() => router.back()} style={{ marginBottom: 12 }} activeOpacity={0.7}>
            <Text style={{ color: '#A5F3FC', fontSize: 17, fontWeight: '600' }}>← Back</Text>
          </TouchableOpacity>
          <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-end' }}>
            <View>
              <Text style={{ color: '#FFF', fontSize: 28, fontWeight: '800' }}>Remittances</Text>
              <Text style={{ color: '#A5F3FC', fontSize: 14, marginTop: 2 }}>{data.length} submissions</Text>
            </View>
            <TouchableOpacity
              style={{ backgroundColor: 'rgba(255,255,255,0.2)', borderRadius: 12, paddingHorizontal: 16, paddingVertical: 10 }}
              onPress={() => router.push('/(app)/remittances/submit')}
              activeOpacity={0.7}
            >
              <Text style={{ color: '#FFF', fontWeight: '700', fontSize: 15 }}>+ Submit</Text>
            </TouchableOpacity>
          </View>
        </View>

        {isLoading ? (
          <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <ActivityIndicator color="#0891B2" size="large" />
          </View>
        ) : (
          <FlatList
            data={data}
            keyExtractor={(item) => item.id}
            refreshControl={<RefreshControl refreshing={isRefetching} onRefresh={refetchAll} tintColor="#0891B2" />}
            ListHeaderComponent={
              unremittedTotal > 0 ? (
                <TouchableOpacity
                  onPress={() => router.push('/(app)/remittances/submit')}
                  style={{ backgroundColor: '#FFF7ED', borderRadius: 16, padding: 18, marginBottom: 16, borderWidth: 1.5, borderColor: '#FED7AA' }}
                  activeOpacity={0.7}
                >
                  <Text style={{ fontSize: 13, fontWeight: '700', color: '#92400E', textTransform: 'uppercase', letterSpacing: 0.3, marginBottom: 4 }}>
                    Unremitted Amount
                  </Text>
                  <Text style={{ fontSize: 28, fontWeight: '800', color: '#9A3412' }}>
                    ₱{Number(unremittedTotal).toLocaleString()}
                  </Text>
                  {unremittedCount > 0 && (
                    <Text style={{ fontSize: 14, color: '#C2410C', marginTop: 4 }}>{unremittedCount} payment{unremittedCount !== 1 ? 's' : ''} pending remittance</Text>
                  )}
                  <Text style={{ fontSize: 14, color: '#EA580C', marginTop: 8, fontWeight: '600' }}>Tap to submit →</Text>
                </TouchableOpacity>
              ) : null
            }
            contentContainerStyle={{ padding: 16, paddingBottom: 32 }}
            renderItem={({ item }) => {
              const st = STATUS_CONFIG[item.status] ?? { color: '#6B7280', bg: '#F1F5F9' };
              return (
                <TouchableOpacity
                  style={{ backgroundColor: '#FFF', borderRadius: 16, padding: 18, marginBottom: 12, borderWidth: 1, borderColor: '#F1F5F9' }}
                  onPress={() => router.push(`/(app)/remittances/${item.id}`)}
                  activeOpacity={0.7}
                >
                  <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
                    <Text style={{ fontSize: 20, fontWeight: '800', color: '#0F172A' }}>₱{Number(item.totalAmount).toLocaleString()}</Text>
                    <View style={{ borderRadius: 20, paddingHorizontal: 12, paddingVertical: 5, backgroundColor: st.bg }}>
                      <Text style={{ fontSize: 13, fontWeight: '700', color: st.color }}>{item.status}</Text>
                    </View>
                  </View>
                  <Text style={{ fontSize: 15, color: '#64748B' }}>{new Date(item.createdAt).toLocaleDateString('en-PH', { year: 'numeric', month: 'long', day: 'numeric' })}</Text>
                  {item.payments?.length > 0 && (
                    <Text style={{ fontSize: 14, color: '#94A3B8', marginTop: 3 }}>{item.payments.length} payment{item.payments.length !== 1 ? 's' : ''}</Text>
                  )}
                </TouchableOpacity>
              );
            }}
            ListEmptyComponent={
              <View style={{ alignItems: 'center', paddingVertical: 60 }}>
                <Text style={{ fontSize: 17, color: '#94A3B8' }}>No remittances yet</Text>
              </View>
            }
          />
        )}
      </View>
    </SafeAreaView>
  );
}
