import { useQuery } from '@tanstack/react-query';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import Constants from 'expo-constants';
import { router } from 'expo-router';
import { useMemo, useState } from 'react';
import { Alert, Pressable, ScrollView, StyleSheet, Text, TextInput, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { ScreenHeader } from '../../src/components/ScreenHeader';
import { api } from '../../src/lib/api';
import { getCustomer } from '../../src/lib/session';
import { syncWalletState } from '../../src/lib/walletSync';

export default function SolarScreen() {
  const solarPurchaseFee = Number(Constants.expoConfig?.extra?.purchaseFee ?? 70);
  const customerQuery = useQuery({ queryKey: ['customer'], queryFn: getCustomer });
  const [company, setCompany] = useState('');
  const [deviceId, setDeviceId] = useState('');
  const [amount, setAmount] = useState('');
  const [pin, setPin] = useState('');
  const [loading, setLoading] = useState(false);

  const companiesQuery = useQuery({
    queryKey: ['solar-companies'],
    queryFn: async () => {
      const response = await api.get('/vtu/companies');
      return response.data?.data?.companies ?? [];
    },
  });

  const previewQuery = useQuery({
    queryKey: ['solar-preview', company, deviceId, amount],
    enabled: !!company && !!deviceId && Number(amount) >= 100,
    queryFn: async () => {
      const response = await api.post('/vtu/preview', {
        company,
        device_id: deviceId,
        amount: Number(amount),
      });
      return response.data?.data ?? null;
    },
  });

  const walletBalance = Number(customerQuery.data?.wallet_balance ?? 0);
  const previewAmount = Number(previewQuery.data?.amount ?? amount ?? 0);
  const previewPlatformFee = Number(previewQuery.data?.platform_fee ?? previewQuery.data?.platformFee ?? solarPurchaseFee);
  const previewCharge = Number(
    previewQuery.data?.customer_charge ??
      previewQuery.data?.customerCharge ??
      previewAmount + previewPlatformFee,
  );
  const charge = useMemo(() => previewCharge, [previewCharge]);
  const canSubmit = company && deviceId && Number(amount) >= 100 && pin.length === 5;

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

    try {
      if (previewQuery.data) {
        const confirmed = await new Promise<boolean>((resolve) => {
          Alert.alert(
            'Confirm Solar Purchase',
            `Company: ${company}\nDevice: ${deviceId}\nAmount: ₦${previewAmount.toLocaleString()}\nPlatform Fee: ₦${solarPurchaseFee.toLocaleString()}\nTotal Charge: ₦${previewCharge.toLocaleString()}`,
            [
              { text: 'Cancel', style: 'cancel', onPress: () => resolve(false) },
              { text: 'Continue', onPress: () => resolve(true) },
            ],
          );
        });

        if (!confirmed) {
          return;
        }
      }

      setLoading(true);
      const response = await api.post('/vtu/purchase', {
        service: 'solar',
        customer_id: customerQuery.data?.id,
        company,
        device_id: deviceId,
        amount: Number(amount),
        transaction_pin: pin,
      });

      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);
      const providerRef = response.data?.data?.provider_reference ?? response.data?.data?.provider?.reference ?? '';
      router.push({
        pathname: '/(app)/receipt',
        params: {
          type: 'Solar',
          reference: response.data?.data?.reference ?? '',
          service: 'solar',
          company: response.data?.data?.company ?? company,
          device_id: response.data?.data?.device_id ?? deviceId,
          amount: String(response.data?.data?.amount ?? amount),
          charged: String(response.data?.data?.charged ?? charge),
          balance_after: String(response.data?.data?.customer_balance_after ?? ''),
          provider_reference: providerRef,
          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 purchase solar right now.'}${debug}`,
      );
    } finally {
      setLoading(false);
    }
  };

  return (
    <SafeAreaView style={styles.safeArea} edges={['top']}>
      <ScrollView contentContainerStyle={styles.content}>
        <ScreenHeader title="Solar PIN" subtitle="Use the live provider flow." onBack={() => router.back()} />
        <View style={styles.balanceCard}>
          <MaterialCommunityIcons name="wallet" size={22} color="#0F5132" />
          <View style={{ flex: 1 }}>
            <Text style={styles.balanceLabel}>Wallet Balance</Text>
            <Text style={styles.balanceValue}>₦{walletBalance.toLocaleString()}</Text>
          </View>
        </View>

        <View style={styles.card}>
          <Text style={styles.sectionLabel}>Company</Text>
          <View style={styles.chipGrid}>
            {(companiesQuery.data ?? [{ id: 0, name: 'SunKing' }]).map((item: any) => (
              <Pressable
                key={String(item.id ?? item.name)}
                onPress={() => setCompany(String(item.name ?? item))}
                style={[styles.chip, company === String(item.name ?? item) && styles.chipActive]}
              >
                <Text style={[styles.chipText, company === String(item.name ?? item) && styles.chipTextActive]}>
                  {String(item.name ?? item)}
                </Text>
              </Pressable>
            ))}
          </View>

          <TextInput placeholder="Meter / Device ID" placeholderTextColor="#94A3B8" value={deviceId} onChangeText={setDeviceId} style={styles.input} />
          <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}>Company: {company || '-'}</Text>
            <Text style={styles.previewText}>Device: {deviceId || '-'}</Text>
            <Text style={styles.previewText}>Amount: ₦{previewAmount.toLocaleString()}</Text>
            <Text style={styles.previewText}>Platform Fee: ₦{solarPurchaseFee.toLocaleString()}</Text>
            <Text style={styles.previewText}>Total Charge: ₦{previewCharge.toLocaleString()}</Text>
            <Text style={styles.previewText}>Balance After: ₦{Math.max(0, walletBalance - previewCharge).toLocaleString()}</Text>
          </View>

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

const styles = StyleSheet.create({
  safeArea: { flex: 1, backgroundColor: '#F4FAF7' },
  content: { padding: 20 },
  balanceCard: { flexDirection: 'row', gap: 12, alignItems: 'center', 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' },
  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' },
});
