import { useQuery } from '@tanstack/react-query';
import { router } from 'expo-router';
import { useMemo, useState } from 'react';
import { Alert, Pressable, StyleSheet, Text, TextInput, View } from 'react-native';
import { ScreenHeader } from '../../src/components/ScreenHeader';
import { FormScreen } from '../../src/components/FormScreen';
import { api } from '../../src/lib/api';
import { getCustomer } from '../../src/lib/session';
import { syncWalletState } from '../../src/lib/walletSync';

export default function AirtimeScreen() {
  const customerQuery = useQuery({ queryKey: ['customer'], queryFn: getCustomer });
  const [networkId, setNetworkId] = useState<number | null>(null);
  const [phone, setPhone] = useState('');
  const [amount, setAmount] = useState('');
  const [pin, setPin] = useState('');
  const [airtimeType, setAirtimeType] = useState<'VTU' | 'Share And Sell'>('VTU');
  const [loading, setLoading] = useState(false);

  const networksQuery = useQuery({
    queryKey: ['airtime-networks'],
    queryFn: async () => {
      const response = await api.get('/vtu/networks', { params: { service: 'airtime' } });
      return response.data?.data?.networks ?? [];
    },
  });

  const selectedNetwork = useMemo(
    () => (networksQuery.data ?? []).find((item: any) => Number(item.id) === Number(networkId)),
    [networkId, networksQuery.data],
  );
  const walletBalance = Number(customerQuery.data?.wallet_balance ?? 0);
  const charge = Number(amount || 0);
  const canSubmit = !!networkId && phone.trim().length >= 10 && charge >= 50 && pin.length === 5;

  const submit = async () => {
    if (!canSubmit) {
      Alert.alert('Validation', 'Please complete every field correctly.');
      return;
    }

    try {
      setLoading(true);
      const response = await api.post('/vtu/purchase', {
        service: 'airtime',
        customer_id: customerQuery.data?.id,
        network_id: networkId,
        phone,
        amount: charge,
        transaction_pin: pin,
        airtime_type: airtimeType,
      });
      await syncWalletState(response.data?.data?.customer_balance_after);
      const providerStatus = String(response.data?.data?.provider?.status ?? 'success').toLowerCase();
      const isSuccess = providerStatus === 'success';
      const receiptMessage = response.data?.data?.provider?.msg ?? (isSuccess ? 'Purchase completed' : 'Purchase failed and wallet refunded.');
      Alert.alert(isSuccess ? 'Success' : 'Purchase failed', receiptMessage);
      router.push({
        pathname: '/(app)/receipt',
        params: {
          type: 'Airtime',
          reference: response.data?.data?.reference ?? '',
          service: 'airtime',
          network: response.data?.data?.network ?? selectedNetwork?.network_name ?? '',
          phone: response.data?.data?.phone ?? phone,
          amount: String(response.data?.data?.amount ?? charge),
          charged: String(response.data?.data?.charged ?? charge),
          balance_after: String(response.data?.data?.customer_balance_after ?? ''),
          status: providerStatus,
          message: receiptMessage,
          timestamp: new Date().toISOString(),
        },
      } as any);
    } catch (e: any) {
      const debug = e?.response?.data?.debug ? `\n\nDEBUG:\n${JSON.stringify(e.response.data.debug, null, 2)}` : '';
      Alert.alert('Purchase failed', `${e?.response?.data?.message ?? 'Unable to buy airtime right now.'}${debug}`);
    } finally {
      setLoading(false);
    }
  };

  return (
    <FormScreen contentStyle={styles.content}>
      <View style={styles.container}>
        <ScreenHeader title="Airtime" subtitle="Buy airtime from the VTU backend." onBack={() => router.back()} />
        <View style={styles.balanceCard}>
          <Text style={styles.balanceLabel}>Wallet Balance</Text>
          <Text style={styles.balanceValue}>₦{walletBalance.toLocaleString()}</Text>
        </View>
        <View style={styles.card}>
          <Text style={styles.sectionLabel}>Network</Text>
          <View style={styles.chipGrid}>
            {(networksQuery.data ?? []).map((item: any) => (
              <Pressable key={item.id} onPress={() => setNetworkId(Number(item.id))} style={[styles.chip, networkId === Number(item.id) && styles.chipActive]}>
                <Text style={[styles.chipText, networkId === Number(item.id) && styles.chipTextActive]}>{item.network_name}</Text>
              </Pressable>
            ))}
          </View>

          <Text style={styles.sectionLabel}>Type</Text>
          <View style={styles.row}>
            {(['VTU', 'Share And Sell'] as const).map((type) => (
              <Pressable key={type} onPress={() => setAirtimeType(type)} style={[styles.typeChip, airtimeType === type && styles.typeChipActive]}>
                <Text style={[styles.typeText, airtimeType === type && styles.typeTextActive]}>{type}</Text>
              </Pressable>
            ))}
          </View>

          <TextInput placeholder="Phone number" placeholderTextColor="#94A3B8" value={phone} onChangeText={setPhone} style={styles.input} keyboardType="phone-pad" />
          <TextInput placeholder="Amount" placeholderTextColor="#94A3B8" value={amount} onChangeText={setAmount} keyboardType="numeric" style={styles.input} />
          <TextInput placeholder="Transaction PIN" placeholderTextColor="#94A3B8" value={pin} onChangeText={setPin} secureTextEntry style={styles.input} maxLength={5} keyboardType="number-pad" />

          <View style={styles.previewCard}>
            <Text style={styles.previewLabel}>Preview</Text>
            <Text style={styles.previewText}>Network: {selectedNetwork?.network_name ?? '-'}</Text>
            <Text style={styles.previewText}>Charge: ₦{charge.toLocaleString()}</Text>
            <Text style={styles.previewText}>Balance After: ₦{Math.max(0, walletBalance - charge).toLocaleString()}</Text>
          </View>

          <Pressable style={[styles.button, !canSubmit && styles.buttonDisabled]} onPress={submit} disabled={loading || !canSubmit}>
            <Text style={styles.buttonText}>{loading ? 'Processing...' : 'Buy Airtime'}</Text>
          </Pressable>
        </View>
      </View>
    </FormScreen>
  );
}

const styles = StyleSheet.create({
  content: { flexGrow: 1 },
  container: { flex: 1, backgroundColor: '#F4FAF7', padding: 20, paddingBottom: 40 },
  balanceCard: { backgroundColor: '#FFFFFF', borderRadius: 18, padding: 16, borderWidth: 1, borderColor: '#D8E7DF', marginBottom: 14 },
  balanceLabel: { color: '#64748B', fontSize: 12, fontWeight: '700' },
  balanceValue: { color: '#062117', fontSize: 24, fontWeight: '900', marginTop: 2 },
  card: { backgroundColor: '#fff', borderRadius: 20, padding: 18, borderWidth: 1, borderColor: '#D8E7DF' },
  sectionLabel: { color: '#062117', fontWeight: '800', marginBottom: 10 },
  chipGrid: { flexDirection: 'row', flexWrap: 'wrap', gap: 8, marginBottom: 12 },
  chip: { paddingHorizontal: 12, paddingVertical: 10, borderRadius: 999, backgroundColor: '#F3F8F5', borderWidth: 1, borderColor: '#D8E7DF' },
  chipActive: { backgroundColor: '#0F5132', borderColor: '#0F5132' },
  chipText: { color: '#0F5132', fontWeight: '700' },
  chipTextActive: { color: '#FFFFFF' },
  row: { flexDirection: 'row', gap: 8, marginBottom: 12 },
  typeChip: { flex: 1, padding: 12, borderRadius: 14, backgroundColor: '#F3F8F5', borderWidth: 1, borderColor: '#D8E7DF', alignItems: 'center' },
  typeChipActive: { backgroundColor: '#0F5132', borderColor: '#0F5132' },
  typeText: { color: '#0F5132', fontWeight: '700' },
  typeTextActive: { color: '#FFFFFF' },
  input: { backgroundColor: '#F3F8F5', borderRadius: 14, padding: 14, marginBottom: 12 },
  previewCard: { backgroundColor: '#F8FBF9', borderRadius: 16, padding: 14, borderWidth: 1, borderColor: '#D8E7DF', marginBottom: 14 },
  previewLabel: { color: '#062117', fontWeight: '800', marginBottom: 8 },
  previewText: { color: '#475569', marginTop: 4 },
  button: { backgroundColor: '#0F5132', borderRadius: 14, padding: 16, alignItems: 'center' },
  buttonDisabled: { opacity: 0.6 },
  buttonText: { color: '#fff', fontWeight: '800' },
});
