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

const STATUS_COLOR: Record<string, string> = { PENDING: '#D97706', CONFIRMED: '#16A34A', DISPUTED: '#DC2626' };
const METHOD_ICON: Record<string, string> = { CASH: '💵', GCASH: '📱', MAYA: '💙', BANK: '🏦' };

export default function RemittanceDetailScreen() {
  const { id } = useLocalSearchParams<{ id: string }>();

  const { data, isLoading } = useQuery({
    queryKey: ['remittance', id],
    queryFn: () => api.get(`/api/v1/remittances/${id}`).then(r => r.data),
  });

  if (isLoading) return (
    <View className="flex-1 items-center justify-center bg-gray-50">
      <ActivityIndicator color="#2563EB" />
    </View>
  );

  const status = data?.status ?? 'PENDING';
  const statusColor = STATUS_COLOR[status] ?? '#6B7280';

  return (
    <View className="flex-1 bg-gray-50">
      <View className="px-4 pt-14 pb-4 bg-primary flex-row items-center">
        <TouchableOpacity onPress={() => router.back()} className="mr-3 p-1">
          <Text className="text-white text-lg">←</Text>
        </TouchableOpacity>
        <View className="flex-1">
          <Text className="text-white font-bold text-lg">Remittance</Text>
          <Text className="text-white/70 text-xs">{data?.createdAt ? new Date(data.createdAt).toLocaleDateString() : ''}</Text>
        </View>
        <View className="rounded-full px-3 py-1" style={{ backgroundColor: `${statusColor}30` }}>
          <Text className="text-xs font-bold" style={{ color: statusColor }}>{status}</Text>
        </View>
      </View>

      <ScrollView className="flex-1 px-4 py-4">
        {/* Summary card */}
        <View className="bg-white rounded-2xl border border-gray-100 p-5 mb-4 items-center">
          <Text className="text-gray-500 text-sm mb-1">Total Amount</Text>
          <Text className="text-4xl font-bold text-gray-900">₱{Number(data?.totalAmount ?? 0).toLocaleString()}</Text>
          {data?.notes && <Text className="text-gray-500 text-sm mt-3 text-center">{data.notes}</Text>}
        </View>

        {/* Details */}
        <View className="bg-white rounded-2xl border border-gray-100 mb-4">
          {[
            { label: 'Submitted by', value: data?.collector?.firstName ? `${data.collector.firstName} ${data.collector.lastName}` : undefined },
            { label: 'Submitted on', value: data?.createdAt ? new Date(data.createdAt).toLocaleString() : undefined },
            { label: 'Confirmed on', value: data?.confirmedAt ? new Date(data.confirmedAt).toLocaleString() : undefined },
            { label: 'Confirmed by', value: data?.confirmedBy?.firstName ? `${data.confirmedBy.firstName} ${data.confirmedBy.lastName}` : undefined },
          ].filter(r => r.value).map((row, i, arr) => (
            <View key={row.label} className={`px-4 py-3 ${i < arr.length - 1 ? 'border-b border-gray-100' : ''}`}>
              <Text className="text-gray-500 text-xs">{row.label}</Text>
              <Text className="text-gray-900 font-medium mt-0.5">{row.value}</Text>
            </View>
          ))}
        </View>

        {/* Included payments */}
        {(data?.payments ?? []).length > 0 && (
          <>
            <Text className="font-semibold text-gray-700 mb-2 px-1">Included Payments ({data.payments.length})</Text>
            {data.payments.map((p: any) => (
              <View key={p.id} className="bg-white rounded-xl p-4 mb-2 border border-gray-100">
                <View className="flex-row justify-between items-start">
                  <View>
                    <Text className="font-medium text-gray-900">
                      {METHOD_ICON[p.paymentMethod] ?? '💳'} {p.client?.firstName} {p.client?.lastName}
                    </Text>
                    <Text className="text-gray-500 text-sm">{p.client?.accountNumber} · {p.paymentMethod}</Text>
                    {p.referenceNumber && <Text className="text-gray-400 text-xs">Ref: {p.referenceNumber}</Text>}
                  </View>
                  <Text className="font-bold text-green-700">₱{Number(p.amount).toLocaleString()}</Text>
                </View>
              </View>
            ))}
          </>
        )}

        <View className="h-8" />
      </ScrollView>
    </View>
  );
}
