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

const METHODS = ['CASH', 'GCASH', 'MAYA', 'BANK'];

export default function RecordPaymentScreen() {
  const [search, setSearch] = 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 (!search.trim()) return;
    setSearching(true);
    try {
      const res = await api.get(`/api/v1/clients?search=${search.trim()}&limit=1`);
      const found = res.data?.data?.[0] ?? res.data?.[0];
      if (found) setClient(found);
      else Alert.alert('Not Found', 'No client found with that account number or name.');
    } catch {
      Alert.alert('Error', 'Search failed.');
    } finally {
      setSearching(false);
    }
  };

  const submit = async () => {
    if (!client) return Alert.alert('Required', 'Search and select a client first.');
    if (!amount || isNaN(Number(amount))) return Alert.alert('Required', 'Enter a valid amount.');
    setLoading(true);
    try {
      await api.post('/api/v1/payments', {
        clientId: client.id,
        amount: Number(amount),
        paymentMethod: method,
        referenceNumber: reference || undefined,
        paymentDate: new Date().toISOString(),
      });
      Alert.alert('Success', 'Payment recorded!', [{ text: 'OK', onPress: () => router.back() }]);
    } catch (e: any) {
      Alert.alert('Error', e?.response?.data?.message ?? 'Payment failed.');
    } finally {
      setLoading(false);
    }
  };

  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">
          <Text className="text-white text-lg">←</Text>
        </TouchableOpacity>
        <Text className="text-white text-xl font-bold">Record Payment</Text>
      </View>
      <ScrollView className="flex-1 px-4 py-4">
        <Text className="font-semibold text-gray-700 mb-2">Search Client</Text>
        <View className="flex-row mb-4">
          <TextInput
            className="flex-1 bg-white border border-gray-200 rounded-xl px-4 py-3 mr-2"
            placeholder="Account # or name"
            value={search}
            onChangeText={setSearch}
          />
          <TouchableOpacity className="bg-primary rounded-xl px-4 items-center justify-center" onPress={searchClient}>
            {searching ? <ActivityIndicator color="white" /> : <Text className="text-white font-semibold">Find</Text>}
          </TouchableOpacity>
        </View>

        {client && (
          <View className="bg-blue-50 border border-blue-200 rounded-xl p-4 mb-4">
            <Text className="font-bold text-blue-900">{client.firstName} {client.lastName}</Text>
            <Text className="text-blue-700 text-sm">{client.accountNumber}</Text>
          </View>
        )}

        <Text className="font-semibold text-gray-700 mb-2">Amount (₱)</Text>
        <TextInput
          className="bg-white border border-gray-200 rounded-xl px-4 py-3 mb-4 text-base"
          placeholder="0.00"
          value={amount}
          onChangeText={setAmount}
          keyboardType="numeric"
        />

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

        <Text className="font-semibold text-gray-700 mb-2">Reference # (optional)</Text>
        <TextInput
          className="bg-white border border-gray-200 rounded-xl px-4 py-3 mb-8"
          placeholder="GCash ref, receipt #, etc."
          value={reference}
          onChangeText={setReference}
        />

        <TouchableOpacity
          className="bg-primary rounded-xl py-4 items-center"
          onPress={submit}
          disabled={loading}
        >
          {loading ? <ActivityIndicator color="white" /> : <Text className="text-white font-bold text-base">Submit Payment</Text>}
        </TouchableOpacity>
      </ScrollView>
    </View>
  );
}
