import { useQuery } from '@tanstack/react-query';
import Constants from 'expo-constants';
import { router } from 'expo-router';
import { useEffect, useState } from 'react';
import { ActivityIndicator, Alert, Pressable, Text, TextInput, View, StyleSheet } 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';

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

export default function WithdrawalScreen() {
  const withdrawalFee = Number(Constants.expoConfig?.extra?.withdrawalFee ?? 50);
  const customerQuery = useQuery({ queryKey: ['customer'], queryFn: getCustomer });
  const [amount, setAmount] = useState('');
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    if (!customerQuery.isLoading && !customerQuery.data) router.replace('/auth/login');
  }, [customerQuery.data, customerQuery.isLoading]);

  const amountValue = Number(amount || 0);
  const walletBalance = Number(customerQuery.data?.wallet_balance ?? 0);
  const totalDeduction = amountValue + withdrawalFee;
  const balanceAfter = Math.max(0, walletBalance - totalDeduction);

  const submit = async () => {
    if (!amountValue || amountValue < 100) {
      Alert.alert('Validation', 'Minimum withdrawal amount is ₦100.');
      return;
    }

    try {
      setSubmitting(true);
      const response = await api.post('/withdrawals/create', {
        customer_id: customerQuery.data?.id,
        amount: amountValue,
      });
      Alert.alert('Success', response.data?.message ?? 'Withdrawal request submitted');
      router.push('/(app)/transactions');
    } catch (error: any) {
      Alert.alert('Withdrawal failed', error?.response?.data?.message ?? 'Unable to submit withdrawal right now.');
    } finally {
      setSubmitting(false);
    }
  };

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

  return (
    <FormScreen contentStyle={styles.content}>
      <View style={styles.container}>
        <ScreenHeader title="Withdrawal" subtitle="Request a withdrawal from your wallet." onBack={() => router.back()} />
        <View style={styles.card}>
          <Text style={styles.label}>Wallet Balance</Text>
          <Text style={styles.balance}>{money(walletBalance)}</Text>
          <Text style={styles.hint}>This workflow matches the web app and submits a pending withdrawal request.</Text>

          <Text style={[styles.label, { marginTop: 18 }]}>Amount to withdraw</Text>
          <TextInput
            value={amount}
            onChangeText={setAmount}
            placeholder="Amount to withdraw"
            placeholderTextColor="#94A3B8"
            keyboardType="number-pad"
            style={styles.input}
          />

          <View style={styles.previewCard}>
            <Text style={styles.previewTitle}>Preview</Text>
            <Text style={styles.previewText}>Withdrawal Amount: {money(amountValue)}</Text>
            <Text style={styles.previewText}>Withdrawal Fee: {money(withdrawalFee)}</Text>
            <Text style={styles.previewText}>Total Deduction: {money(totalDeduction)}</Text>
            <Text style={styles.previewText}>Balance After: {money(balanceAfter)}</Text>
          </View>

          <Pressable style={styles.button} onPress={submit} disabled={submitting}>
            <Text style={styles.buttonText}>{submitting ? 'Submitting...' : 'Submit Withdrawal'}</Text>
          </Pressable>
        </View>
      </View>
    </FormScreen>
  );
}

const styles = StyleSheet.create({
  loading: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: '#F4FAF7' },
  content: { flexGrow: 1 },
  container: { flex: 1, backgroundColor: '#F4FAF7', padding: 20, paddingBottom: 40 },
  card: { backgroundColor: '#FFFFFF', borderRadius: 24, padding: 20, borderWidth: 1, borderColor: '#D8E7DF' },
  label: { color: '#64748B', fontSize: 13, fontWeight: '700' },
  balance: { color: '#062117', fontSize: 34, fontWeight: '900', marginTop: 6 },
  hint: { color: '#475569', marginTop: 8, lineHeight: 20 },
  input: { marginTop: 10, backgroundColor: '#F3F8F5', borderRadius: 16, paddingHorizontal: 16, paddingVertical: 14, fontSize: 16, color: '#062117' },
  previewCard: { marginTop: 14, backgroundColor: '#F8FBF9', borderRadius: 16, padding: 14, borderWidth: 1, borderColor: '#D8E7DF' },
  previewTitle: { color: '#062117', fontWeight: '800', marginBottom: 8 },
  previewText: { color: '#475569', marginTop: 4 },
  button: { backgroundColor: '#0F5132', borderRadius: 16, alignItems: 'center', paddingVertical: 16, marginTop: 18 },
  buttonText: { color: '#FFFFFF', fontWeight: '800', fontSize: 16 },
});
