import { View, Text, ScrollView, TouchableOpacity, ActivityIndicator } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useLocalSearchParams, router } from 'expo-router';
import { useQuery } from '@tanstack/react-query';
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' },
};

function InfoRow({ label, value, isLast }: { label: string; value?: string | null; isLast?: boolean }) {
  if (!value) return null;
  return (
    <View style={{ paddingHorizontal: 20, paddingVertical: 16, borderBottomWidth: isLast ? 0 : 1, borderBottomColor: '#F1F5F9' }}>
      <Text style={{ fontSize: 12, fontWeight: '600', color: '#94A3B8', textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 4 }}>{label}</Text>
      <Text style={{ fontSize: 17, fontWeight: '500', color: '#0F172A' }}>{value}</Text>
    </View>
  );
}

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?.data ?? r.data),
  });

  if (isLoading) {
    return (
      <SafeAreaView style={{ flex: 1, backgroundColor: '#0891B2' }} edges={['top']}>
        <View style={{ flex: 1, backgroundColor: '#F8FAFC', alignItems: 'center', justifyContent: 'center' }}>
          <ActivityIndicator color="#0891B2" size="large" />
        </View>
      </SafeAreaView>
    );
  }

  const status = data?.status ?? 'PENDING';
  const st = STATUS_CONFIG[status] ?? { color: '#6B7280', bg: '#F1F5F9' };
  const payments: any[] = data?.payments ?? [];

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: '#0891B2' }} edges={['top']}>
      <View style={{ flex: 1, backgroundColor: '#F8FAFC' }}>
        {/* Header */}
        <View style={{ backgroundColor: '#0891B2', paddingHorizontal: 16, 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-start' }}>
            <View>
              <Text style={{ color: '#FFF', fontSize: 22, fontWeight: '800' }}>Remittance</Text>
              <Text style={{ color: '#A5F3FC', fontSize: 14, marginTop: 2 }}>
                {data?.createdAt ? new Date(data.createdAt).toLocaleDateString('en-PH', { year: 'numeric', month: 'long', day: 'numeric' }) : ''}
              </Text>
            </View>
            <View style={{ borderRadius: 20, paddingHorizontal: 14, paddingVertical: 7, backgroundColor: st.bg }}>
              <Text style={{ fontSize: 13, fontWeight: '700', color: st.color }}>{status}</Text>
            </View>
          </View>
        </View>

        <ScrollView style={{ flex: 1 }} contentContainerStyle={{ padding: 16, paddingBottom: 40 }}>
          {/* Total amount card */}
          <View style={{ backgroundColor: '#FFF', borderRadius: 20, padding: 24, marginBottom: 16, alignItems: 'center', borderWidth: 1, borderColor: '#F1F5F9' }}>
            <Text style={{ fontSize: 13, fontWeight: '600', color: '#94A3B8', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 8 }}>Total Amount</Text>
            <Text style={{ fontSize: 38, fontWeight: '800', color: '#0F172A' }}>₱{Number(data?.totalAmount ?? 0).toLocaleString()}</Text>
            {payments.length > 0 && (
              <Text style={{ fontSize: 15, color: '#64748B', marginTop: 6 }}>{payments.length} payment{payments.length !== 1 ? 's' : ''} included</Text>
            )}
            {data?.notes && (
              <Text style={{ fontSize: 15, color: '#64748B', marginTop: 8, textAlign: 'center', fontStyle: 'italic' }}>"{data.notes}"</Text>
            )}
          </View>

          {/* Details */}
          <View style={{ backgroundColor: '#FFF', borderRadius: 20, borderWidth: 1, borderColor: '#F1F5F9', marginBottom: 16, overflow: 'hidden' }}>
            <InfoRow label="Submitted by"
              value={data?.collector?.firstName ? `${data.collector.firstName} ${data.collector.lastName}` : undefined} />
            <InfoRow label="Submitted on"
              value={data?.createdAt ? new Date(data.createdAt).toLocaleString('en-PH') : undefined} />
            <InfoRow label="Confirmed on"
              value={data?.confirmedAt ? new Date(data.confirmedAt).toLocaleString('en-PH') : undefined} />
            <InfoRow label="Confirmed by"
              value={data?.confirmedBy?.firstName ? `${data.confirmedBy.firstName} ${data.confirmedBy.lastName}` : undefined}
              isLast />
          </View>

          {/* Payments breakdown */}
          {payments.length > 0 && (
            <>
              <Text style={{ fontSize: 16, fontWeight: '700', color: '#0F172A', marginBottom: 10 }}>
                Payments ({payments.length})
              </Text>
              {payments.map((p: any) => (
                <View key={p.id} style={{ backgroundColor: '#FFF', borderRadius: 16, padding: 18, marginBottom: 10, borderWidth: 1, borderColor: '#F1F5F9' }}>
                  <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                    <View style={{ flex: 1 }}>
                      <Text style={{ fontSize: 16, fontWeight: '700', color: '#0F172A' }}>
                        {p.client?.firstName} {p.client?.lastName}
                      </Text>
                      <Text style={{ fontSize: 14, color: '#64748B', marginTop: 3 }}>
                        {p.client?.accountNumber} · {p.channel ?? p.paymentMethod}
                      </Text>
                      {p.referenceNumber && (
                        <Text style={{ fontSize: 13, color: '#94A3B8', marginTop: 2 }}>Ref: {p.referenceNumber}</Text>
                      )}
                    </View>
                    <Text style={{ fontSize: 18, fontWeight: '800', color: '#166534' }}>
                      ₱{Number(p.amount).toLocaleString()}
                    </Text>
                  </View>
                </View>
              ))}
            </>
          )}
        </ScrollView>
      </View>
    </SafeAreaView>
  );
}
