import { useState } from 'react';
import { View, Text, TextInput, TouchableOpacity, ScrollView, Alert, ActivityIndicator } from 'react-native';
import { useRouter } from 'expo-router';
import { api } from '../../../services/api';

const METHODS = ['Cash', 'GCash', 'Maya', 'Bank Transfer'];

export default function RecordPaymentScreen() {
  const router = useRouter();
  const [accountNumber, setAccountNumber] = useState('');
  const [client, setClient] = useState<any>(null);
  const [amount, setAmount] = useState('');
  const [method, setMethod] = useState('Cash');
  const [reference, setReference] = useState('');
  const [loading, setLoading] = useState(false);
  const [searching, setSearching] = useState(false);

  const searchClient = async () => {
    if (!accountNumber.trim()) return;
    setSearching(true);
    try {
      const res = await api.get(`/api/v1/clients?accountNumber=${accountNumber.trim()}`);
      const clients = res.data?.data ?? res.data?.results ?? [];
      setClient(clients[0] ?? null);
      if (!clients[0]) Alert.alert('Not found', 'No client with that account number.');
    } catch { Alert.alert('Error', 'Could not search clients.'); }
    finally { setSearching(false); }
  };

  const submit = async () => {
    if (!client || !amount) return Alert.alert('Required', 'Select a client and enter amount.');
    setLoading(true);
    try {
      await api.post('/api/v1/payments', {
        clientId: client.id,
        amount: parseFloat(amount),
        paymentMethod: method.toLowerCase().replace(' ', '_'),
        referenceNumber: reference || undefined,
        paymentDate: new Date().toISOString().split('T')[0],
      });
      Alert.alert('Success', 'Payment recorded!', [{ text: 'OK', onPress: () => router.back() }]);
    } catch (e: any) {
      Alert.alert('Failed', e?.response?.data?.message ?? 'Could not record payment.');
    } finally { setLoading(false); }
  };

  return (
    <ScrollView className="flex-1 bg-gray-50 pt-14">
      <TouchableOpacity className="px-4 mb-4" onPress={() => router.back()}>
        <Text className="text-primary">← Back</Text>
      </TouchableOpacity>
      <Text className="text-2xl font-bold text-gray-900 px-4 mb-6">Record Payment</Text>

      <View className="bg-white mx-4 rounded-2xl p-5 border border-gray-100 mb-4">
        <Text className="text-sm font-medium text-gray-700 mb-2">Account Number</Text>
        <View className="flex-row gap-2">
          <TextInput
            className="flex-1 border border-gray-300 rounded-xl px-3 py-2.5 text-sm bg-gray-50"
            placeholder="e.g. 2024-0001"
            value={accountNumber}
            onChangeText={setAccountNumber}
          />
          <TouchableOpacity className="bg-primary rounded-xl px-4 items-center justify-center" onPress={searchClient}>
            {searching ? <ActivityIndicator color="#fff" size="small" /> : <Text className="text-white font-medium text-sm">Find</Text>}
          </TouchableOpacity>
        </View>
        {client && (
          <View className="mt-3 bg-blue-50 rounded-xl p-3">
            <Text className="text-primary font-semibold">{client.name}</Text>
            <Text className="text-gray-500 text-xs">{client.accountNumber} · {client.status}</Text>
          </View>
        )}
      </View>

      <View className="bg-white mx-4 rounded-2xl p-5 border border-gray-100 mb-4">
        <Text className="text-sm font-medium text-gray-700 mb-2">Amount (₱)</Text>
        <TextInput
          className="border border-gray-300 rounded-xl px-3 py-2.5 text-sm bg-gray-50"
          placeholder="0.00"
          value={amount}
          onChangeText={setAmount}
          keyboardType="decimal-pad"
        />

        <Text className="text-sm font-medium text-gray-700 mt-4 mb-2">Payment Method</Text>
        <View className="flex-row flex-wrap gap-2">
          {METHODS.map(m => (
            <TouchableOpacity
              key={m}
              className={`px-4 py-2 rounded-xl border ${method === m ? 'bg-primary border-primary' : 'border-gray-200 bg-white'}`}
              onPress={() => setMethod(m)}
            >
              <Text className={`text-sm font-medium ${method === m ? 'text-white' : 'text-gray-700'}`}>{m}</Text>
            </TouchableOpacity>
          ))}
        </View>

        <Text className="text-sm font-medium text-gray-700 mt-4 mb-2">Reference # (optional)</Text>
        <TextInput
          className="border border-gray-300 rounded-xl px-3 py-2.5 text-sm bg-gray-50"
          placeholder="GCash ref / OR number"
          value={reference}
          onChangeText={setReference}
        />
      </View>

      <TouchableOpacity
        className={`mx-4 rounded-2xl py-4 items-center mb-8 ${loading ? 'bg-blue-400' : 'bg-primary'}`}
        onPress={submit}
        disabled={loading}
      >
        {loading ? <ActivityIndicator color="#fff" /> : <Text className="text-white font-semibold text-base">Record Payment</Text>}
      </TouchableOpacity>
    </ScrollView>
  );
}
