import { MaterialCommunityIcons } from '@expo/vector-icons';
import { useMutation, useQuery } from '@tanstack/react-query';
import { router } from 'expo-router';
import { useMemo, useRef, useState } from 'react';
import { ActivityIndicator, 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';

function money(value?: number) {
  return `₦${Number(value || 0).toLocaleString()}`;
}

export default function FundWalletScreen() {
  const scrollRef = useRef<ScrollView | null>(null);
  const customerQuery = useQuery({
    queryKey: ['customer'],
    queryFn: getCustomer,
  });
  const [amount, setAmount] = useState('');
  const [senderName, setSenderName] = useState('');
  const [step, setStep] = useState<'amount' | 'details'>('amount');
  const [funding, setFunding] = useState<any>(null);
  const customer = customerQuery.data;

  const createMutation = useMutation({
    mutationFn: async () => {
      const response = await api.post('/funding/create', {
        customer_id: customer?.id,
        amount: Number(amount),
      });
      return response.data?.data?.funding;
    },
    onSuccess: (data) => {
      setFunding(data);
      setStep('details');
    },
  });

  const confirmMutation = useMutation({
    mutationFn: async () => {
      const response = await api.post('/funding/confirm', {
        customer_id: customer?.id,
        reference: funding?.reference,
        sender_name: senderName.trim(),
      });
      return response.data;
    },
    onSuccess: async () => {
      await syncWalletState();
      router.replace({
        pathname: '/(app)/receipt',
        params: {
          type: 'Funding',
          reference: funding?.reference,
          service: 'funding',
          company: 'OPAY',
          amount: String(funding?.amount ?? ''),
          charged: String(funding?.total_amount ?? ''),
          balance_after: String(customer?.wallet_balance ?? 0),
          status: 'processing',
          message: 'Payment confirmation received. Your wallet will be credited soon.',
          timestamp: new Date().toISOString(),
        },
      });
    },
  });

  const amountNumber = Number(amount || 0);
  const fee = 0;
  const total = amountNumber + fee;
  const canContinue = amountNumber >= 500 && !createMutation.isPending;
  const canConfirm = senderName.trim().length > 0 && !confirmMutation.isPending;

  const details = useMemo(() => {
    if (!funding) return null;
    return [
      { label: 'Bank Name', value: 'OPAY' },
      { label: 'Account Name', value: 'Green Light Solar Service.' },
      { label: 'Account Number', value: '6110634897' },
      { label: 'Payment Reference', value: funding.reference },
      { label: 'Amount', value: money(funding.amount) },
      { label: 'Processing Fee', value: money(funding.fee) },
      { label: 'Total to Pay', value: money(funding.total_amount) },
    ];
  }, [funding]);

  if (customerQuery.isLoading && !customer) {
    return (
      <View style={styles.loading}>
        <ActivityIndicator size="large" color="#16A34A" />
      </View>
    );
  }

  return (
    <SafeAreaView style={styles.safeArea} edges={['top']}>
      <ScrollView
        ref={scrollRef}
        contentContainerStyle={styles.container}
        showsVerticalScrollIndicator={false}
        keyboardShouldPersistTaps="handled"
        keyboardDismissMode="on-drag"
      >
        <ScreenHeader title="Fund Wallet" subtitle="Follow the same transfer flow as the web app" />

        <View style={styles.balanceCard}>
          <Text style={styles.balanceLabel}>Wallet Balance</Text>
          <Text style={styles.balanceValue}>{money(customer?.wallet_balance ?? 0)}</Text>
          <Text style={styles.balanceHint}>Funding requests are created first, then confirmed after payment.</Text>
        </View>

        {step === 'amount' ? (
          <View style={styles.card}>
            <Text style={styles.cardTitle}>Enter Amount</Text>
            <Text style={styles.cardHint}>Minimum funding amount is ₦500</Text>
            <View style={styles.inputWrap}>
              <Text style={styles.currency}>₦</Text>
              <TextInput
                value={amount}
                onChangeText={setAmount}
                keyboardType="numeric"
                placeholder="Amount to fund"
                placeholderTextColor="#94A3B8"
                style={styles.input}
              />
            </View>
            <View style={styles.summaryBox}>
              <Row label="Amount" value={money(amountNumber)} />
              <Row label="Processing Fee" value={money(fee)} />
              <View style={styles.divider} />
              <Row label="Total" value={money(total)} strong />
            </View>
            {createMutation.isError ? <Text style={styles.errorText}>{getErrorMessage(createMutation.error)}</Text> : null}
            <Pressable
              style={[styles.primaryButton, !canContinue ? styles.disabledButton : null]}
              onPress={() => createMutation.mutate()}
              disabled={!canContinue}
            >
              {createMutation.isPending ? <ActivityIndicator color="#fff" /> : <Text style={styles.primaryButtonText}>Continue</Text>}
            </Pressable>
          </View>
        ) : null}

        {step === 'details' && funding ? (
          <View style={styles.card}>
            <View style={styles.cardHeaderRow}>
              <View>
                <Text style={styles.cardTitle}>Transfer Details</Text>
                <Text style={styles.cardHint}>Use the account details below exactly as shown.</Text>
              </View>
              <View style={styles.activePill}>
                <Text style={styles.activePillText}>Active</Text>
              </View>
            </View>

            <View style={styles.infoCard}>
              {details?.map((item) => (
                <View key={item.label} style={styles.infoRow}>
                  <Text style={styles.infoLabel}>{item.label}</Text>
                  <Text style={styles.infoValue}>{item.value}</Text>
                </View>
              ))}
            </View>

            <View style={styles.warnBox}>
              <MaterialCommunityIcons name="alert-circle-outline" size={18} color="#B45309" />
              <Text style={styles.warnText}>
                IMPORTANT: Paste the payment reference in your bank transfer narration for fast approval.
              </Text>
            </View>

            <Text style={styles.fieldLabel}>Your Bank Account Name</Text>
            <TextInput
              value={senderName}
              onChangeText={setSenderName}
              placeholder="Enter the name on your bank account"
              placeholderTextColor="#94A3B8"
              style={styles.textInput}
              onFocus={() => {
                requestAnimationFrame(() => {
                  scrollRef.current?.scrollToEnd({ animated: true });
                });
              }}
            />
            <Text style={styles.helperText}>We use this to verify your transfer automatically.</Text>

            {confirmMutation.isError ? <Text style={styles.errorText}>{getErrorMessage(confirmMutation.error)}</Text> : null}

            <Pressable
              style={[styles.primaryButton, !canConfirm ? styles.disabledButton : null]}
              onPress={() => confirmMutation.mutate()}
              disabled={!canConfirm}
            >
              {confirmMutation.isPending ? <ActivityIndicator color="#fff" /> : <Text style={styles.primaryButtonText}>I&apos;ve Sent the Money</Text>}
            </Pressable>

            <Pressable style={styles.secondaryButton} onPress={() => setStep('amount')}>
              <Text style={styles.secondaryButtonText}>Change Amount</Text>
            </Pressable>
          </View>
        ) : null}
      </ScrollView>
    </SafeAreaView>
  );
}

function Row({ label, value, strong }: { label: string; value: string; strong?: boolean }) {
  return (
    <View style={styles.row}>
      <Text style={[styles.rowLabel, strong ? styles.rowLabelStrong : null]}>{label}</Text>
      <Text style={[styles.rowValue, strong ? styles.rowValueStrong : null]}>{value}</Text>
    </View>
  );
}

function getErrorMessage(error: unknown) {
  if (typeof error !== 'object' || error === null) return 'Something went wrong.';
  const anyError = error as any;
  return anyError?.response?.data?.message ?? anyError?.message ?? 'Something went wrong.';
}

const styles = StyleSheet.create({
  safeArea: { flex: 1, backgroundColor: '#F4FAF7' },
  container: { paddingHorizontal: 20, paddingTop: 12, paddingBottom: 40 },
  loading: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: '#F4FAF7' },
  balanceCard: { backgroundColor: '#16A34A', borderRadius: 24, padding: 20, marginBottom: 16 },
  balanceLabel: { color: '#E7FBEF', fontWeight: '700' },
  balanceValue: { color: '#FFFFFF', fontSize: 34, fontWeight: '900', marginTop: 6 },
  balanceHint: { color: '#ECFDF5', marginTop: 6, opacity: 0.92 },
  card: { backgroundColor: '#FFFFFF', borderRadius: 24, padding: 18, borderWidth: 1, borderColor: '#D8E7DF', marginBottom: 14 },
  cardTitle: { color: '#062117', fontSize: 18, fontWeight: '900' },
  cardHint: { color: '#587267', marginTop: 4 },
  inputWrap: { flexDirection: 'row', alignItems: 'center', backgroundColor: '#F8FBF9', borderRadius: 18, borderWidth: 1, borderColor: '#D8E7DF', paddingHorizontal: 14, marginTop: 14 },
  currency: { color: '#062117', fontSize: 18, fontWeight: '900' },
  input: { flex: 1, paddingVertical: 16, color: '#062117', fontSize: 22, fontWeight: '900', marginLeft: 8 },
  summaryBox: { backgroundColor: '#F8FBF9', borderRadius: 18, borderWidth: 1, borderColor: '#E3EFE8', padding: 14, marginTop: 14 },
  row: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', paddingVertical: 6 },
  rowLabel: { color: '#64748B', fontWeight: '700' },
  rowValue: { color: '#062117', fontWeight: '800' },
  rowLabelStrong: { color: '#062117' },
  rowValueStrong: { color: '#16A34A', fontSize: 16 },
  divider: { height: 1, backgroundColor: '#E3EFE8', marginVertical: 8 },
  errorText: { color: '#DC2626', marginTop: 12, fontWeight: '700' },
  primaryButton: { backgroundColor: '#16A34A', borderRadius: 16, paddingVertical: 14, alignItems: 'center', marginTop: 14 },
  primaryButtonText: { color: '#fff', fontWeight: '900' },
  disabledButton: { opacity: 0.55 },
  cardHeaderRow: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12 },
  activePill: { backgroundColor: '#16A34A', paddingHorizontal: 12, paddingVertical: 6, borderRadius: 999 },
  activePillText: { color: '#fff', fontSize: 11, fontWeight: '900' },
  infoCard: { backgroundColor: '#FFFFFF', borderRadius: 18, borderWidth: 1, borderColor: '#E3EFE8', marginTop: 16, overflow: 'hidden' },
  infoRow: { paddingHorizontal: 14, paddingVertical: 12, borderBottomWidth: 1, borderBottomColor: '#EAF2ED' },
  infoLabel: { color: '#64748B', fontSize: 12, fontWeight: '700' },
  infoValue: { color: '#062117', fontWeight: '900', marginTop: 3 },
  warnBox: { flexDirection: 'row', gap: 10, alignItems: 'flex-start', backgroundColor: '#FFFBEB', borderRadius: 16, padding: 14, marginTop: 14, borderWidth: 1, borderColor: '#FDE68A' },
  warnText: { flex: 1, color: '#92400E', fontWeight: '700', lineHeight: 20 },
  fieldLabel: { color: '#062117', fontWeight: '800', marginTop: 16, marginBottom: 8 },
  textInput: { backgroundColor: '#F8FBF9', borderRadius: 16, borderWidth: 1, borderColor: '#D8E7DF', paddingHorizontal: 14, paddingVertical: 14, color: '#062117', fontWeight: '700' },
  helperText: { color: '#587267', marginTop: 6, fontSize: 12 },
  secondaryButton: { backgroundColor: '#E8F2ED', borderRadius: 16, paddingVertical: 14, alignItems: 'center', marginTop: 10 },
  secondaryButtonText: { color: '#0F5132', fontWeight: '900' },
});
