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

const STATUS_COLOR: Record<string, string> = { PENDING: '#D97706', CONFIRMED: '#16A34A', DISPUTED: '#DC2626' };

export default function RemittancesScreen() {
  const { data, isLoading, refetch, isRefetching } = useQuery({
    queryKey: ['remittances'],
    queryFn: () => api.get('/api/v1/remittances?limit=50').then(r => r.data?.data ?? r.data),
  });

  return (
    <View className="flex-1 bg-gray-50">
      <View className="px-4 pt-14 pb-4 bg-primary flex-row justify-between items-center">
        <Text className="text-white text-xl font-bold">Remittances</Text>
        <TouchableOpacity className="bg-white/20 rounded-lg px-3 py-1.5" onPress={() => router.push('/(app)/remittances/submit')}>
          <Text className="text-white text-sm font-semibold">+ Submit</Text>
        </TouchableOpacity>
      </View>
      {isLoading ? (
        <View className="flex-1 items-center justify-center"><ActivityIndicator color="#2563EB" /></View>
      ) : (
        <FlatList
          data={data ?? []}
          keyExtractor={(item) => item.id}
          refreshControl={<RefreshControl refreshing={isRefetching} onRefresh={refetch} />}
          contentContainerStyle={{ padding: 16 }}
          renderItem={({ item }) => (
            <TouchableOpacity
              className="bg-white rounded-xl p-4 mb-2 border border-gray-100"
              onPress={() => router.push(`/(app)/remittances/${item.id}`)}
            >
              <View className="flex-row justify-between">
                <Text className="font-semibold text-gray-900">₱{Number(item.totalAmount).toLocaleString()}</Text>
                <View className="rounded-full px-2 py-0.5" style={{ backgroundColor: `${STATUS_COLOR[item.status] ?? '#6B7280'}20` }}>
                  <Text className="text-xs font-medium" style={{ color: STATUS_COLOR[item.status] ?? '#6B7280' }}>{item.status}</Text>
                </View>
              </View>
              <Text className="text-gray-500 text-sm mt-1">{new Date(item.createdAt).toLocaleDateString()}</Text>
            </TouchableOpacity>
          )}
          ListEmptyComponent={<View className="items-center py-16"><Text className="text-gray-400">No remittances yet</Text></View>}
        />
      )}
    </View>
  );
}
