import { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, ScrollView, Alert, ActivityIndicator } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { router } from 'expo-router';
import { useQuery } from '@tanstack/react-query';
import { api } from '../../../services/api';

export default function SubmitRemittanceScreen() {
  const [notes, setNotes] = useState('');
  const [loading, setLoading] = useState(false);

  // Fetch unremitted payments — correct endpoint is GET /api/v1/payments/unremitted
  const { data: unremittedData, isLoading: loadingUnremitted } = useQuery({
    queryKey: ['unremitted'],
    queryFn: () => api.get('/api/v1/payments/unremitted').then(r => r.data).catch(() => []),
  });

  const unremittedPayments: any[] = Array.isArray(unremittedData) ? unremittedData : [];
  const totalAmount = unremittedPayments.reduce((s: number, p: any) => s + Number(p.amount ?? 0), 0);

  const submit = async () => {
    if (totalAmount <= 0) return Alert.alert('Nothing to Submit', 'You have no unremitted payments to submit.');
    setLoading(true);
    try {
      const paymentIds = unremittedPayments.map((p: any) => p.id);
      await api.post('/api/v1/remittances', { paymentIds, notes: notes.trim() || undefined });
      Alert.alert('Submitted!', `₱${Number(totalAmount).toLocaleString()} remittance submitted.`, [
        { text: 'OK', onPress: () => router.back() },
      ]);
    } catch (e: any) {
      Alert.alert('Error', e?.response?.data?.message ?? 'Submission failed. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: '#0891B2' }} edges={['top']}>
      <View style={{ flex: 1, backgroundColor: '#F8FAFC' }}>
        <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>
          <Text style={{ color: '#FFF', fontSize: 28, fontWeight: '800' }}>Submit Remittance</Text>
          <Text style={{ color: '#A5F3FC', fontSize: 14, marginTop: 2 }}>End-of-day collection</Text>
        </View>

        <ScrollView style={{ flex: 1 }} contentContainerStyle={{ padding: 16 }} keyboardShouldPersistTaps="handled">
          {/* Total amount summary card */}
          <View style={{ backgroundColor: '#FFF', borderRadius: 20, padding: 20, marginBottom: 20, alignItems: 'center', borderWidth: 1, borderColor: '#F1F5F9' }}>
            <Text style={{ fontSize: 14, fontWeight: '600', color: '#94A3B8', textTransform: 'uppercase', letterSpacing: 0.3, marginBottom: 8 }}>Total to Remit</Text>
            {loadingUnremitted ? (
              <ActivityIndicator color="#0891B2" size="large" />
            ) : (
              <>
                <Text style={{ fontSize: 36, fontWeight: '800', color: totalAmount > 0 ? '#059669' : '#94A3B8' }}>
                  ₱{Number(totalAmount).toLocaleString()}
                </Text>
                {unremittedPayments.length > 0 && (
                  <Text style={{ fontSize: 14, color: '#64748B', marginTop: 6 }}>
                    From {unremittedPayments.length} collection{unremittedPayments.length !== 1 ? 's' : ''}
                  </Text>
                )}
              </>
            )}
          </View>

          {/* Breakdown of payments */}
          {unremittedPayments.length > 0 && (
            <View style={{ marginBottom: 20 }}>
              <Text style={{ fontSize: 16, fontWeight: '700', color: '#0F172A', marginBottom: 10 }}>Breakdown</Text>
              {unremittedPayments.map((p: any) => (
                <View key={p.id} style={{ backgroundColor: '#FFF', borderRadius: 14, padding: 16, marginBottom: 8, flexDirection: 'row', justifyContent: 'space-between', borderWidth: 1, borderColor: '#F1F5F9' }}>
                  <View>
                    <Text style={{ fontSize: 16, fontWeight: '600', color: '#0F172A' }}>{p.client?.firstName} {p.client?.lastName}</Text>
                    <Text style={{ fontSize: 14, color: '#64748B', marginTop: 2 }}>{p.channel} · {p.client?.accountNumber}</Text>
                  </View>
                  <Text style={{ fontSize: 17, fontWeight: '800', color: '#166534' }}>₱{Number(p.amount).toLocaleString()}</Text>
                </View>
              ))}
            </View>
          )}

          {/* Notes */}
          <Text style={{ fontSize: 16, fontWeight: '700', color: '#0F172A', marginBottom: 8 }}>Notes <Text style={{ fontWeight: '400', color: '#94A3B8' }}>(optional)</Text></Text>
          <TextInput
            style={{ backgroundColor: '#FFF', borderWidth: 1.5, borderColor: '#E2E8F0', borderRadius: 14, paddingHorizontal: 18, paddingVertical: 14, fontSize: 16, color: '#0F172A', marginBottom: 24, minHeight: 80, textAlignVertical: 'top' }}
            placeholder="Any remarks or notes for admin..."
            placeholderTextColor="#94A3B8"
            value={notes}
            onChangeText={setNotes}
            multiline
          />

          <TouchableOpacity
            style={{ backgroundColor: totalAmount > 0 ? '#059669' : '#CBD5E1', borderRadius: 14, paddingVertical: 18, alignItems: 'center' }}
            onPress={submit}
            disabled={loading || loadingUnremitted || totalAmount <= 0}
            activeOpacity={0.8}
          >
            {loading ? <ActivityIndicator color="#FFF" /> : <Text style={{ color: '#FFF', fontSize: 17, fontWeight: '700' }}>Submit ₱{Number(totalAmount).toLocaleString()}</Text>}
          </TouchableOpacity>
          <View style={{ height: 32 }} />
        </ScrollView>
      </View>
    </SafeAreaView>
  );
}
