import React, { useState, useEffect } from 'react';
import {
  View, Text, StyleSheet, ScrollView, TouchableOpacity,
  ActivityIndicator, Alert, Image, Dimensions, SafeAreaView, StatusBar, Platform
} from 'react-native';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { Colors } from '@/constants/theme';
import api from '@/services/api';
import { useColorScheme } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import * as ImagePicker from 'expo-image-picker';
import Animated, { FadeInDown, FadeInUp } from 'react-native-reanimated';

const { width } = Dimensions.get('window');

export default function BookingPaymentScreen() {
  const { id, amount: initialAmount, currency: initialCurrency } = useLocalSearchParams<{ id: string; amount: string; currency: string }>();
  const router = useRouter();
  const colorScheme = useColorScheme() ?? 'light';
  const theme = Colors[colorScheme as 'light' | 'dark'];

  const [selectedMethod, setSelectedMethod] = useState<'cash' | 'bank_transfer' | null>(null);
  const [receipt, setReceipt] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [fetchingDetails, setFetchingDetails] = useState(true);
  const [paymentInfo, setPaymentInfo] = useState<any>(null);

  useEffect(() => {
    const fetchPaymentDetails = async () => {
      try {
        const response = await api.get(`/user/booking/show-payment/${id}`);
        if (response.data?.code === 200) {
          setPaymentInfo(response.data);
        }
      } catch (error) {
        console.error('Error fetching payment details:', error);
      } finally {
        setFetchingDetails(false);
      }
    };
    fetchPaymentDetails();
  }, [id]);

  const pickImage = async () => {
    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: false,
      quality: 0.8,
    });
    if (!result.canceled) {
      setReceipt(result.assets[0]);
    }
  };

  const handlePay = async () => {
    if (!selectedMethod) {
      Alert.alert('Atenção', 'Escolha um método de pagamento.');
      return;
    }
    if (selectedMethod === 'bank_transfer' && !receipt) {
      Alert.alert('Atenção', 'Anexe o comprovativo de transferência.');
      return;
    }

    setLoading(true);
    try {
      const formData = new FormData();
      formData.append('booking_id', id as string);
      formData.append('payment_type', selectedMethod);

      if (selectedMethod === 'bank_transfer' && receipt) {
        formData.append('payment_receipt', {
          uri: receipt.uri,
          type: receipt.mimeType ?? 'image/jpeg',
          name: receipt.fileName ?? 'receipt.jpg',
        } as any);
      }

      const response = await api.post('/user/booking/process-payment', formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
      });

      if (response.data?.code === 200) {
        Alert.alert('Sucesso', 'Pagamento processado com sucesso.', [
          { text: 'OK', onPress: () => router.back() },
        ]);
      } else {
        Alert.alert('Erro', response.data?.message ?? 'Erro ao processar pagamento.');
      }
    } catch (error: any) {
      Alert.alert('Erro', 'Não foi possível processar o pagamento.');
    } finally {
      setLoading(false);
    }
  };

  const amount = paymentInfo?.booking?.total_amount ?? initialAmount;
  const currency = paymentInfo?.currency ?? initialCurrency;

  if (fetchingDetails) {
    return (
      <View style={[styles.loaderContainer, { backgroundColor: theme.background }]}>
        <ActivityIndicator size="large" color={theme.primary} />
      </View>
    );
  }

  return (
    <View style={[styles.container, { backgroundColor: theme.background }]}>
      <StatusBar barStyle={colorScheme === 'dark' ? 'light-content' : 'dark-content'} />
      
      {/* AppBar */}
      <View style={[styles.appBar, { backgroundColor: theme.background }]}>
        <TouchableOpacity onPress={() => router.back()} style={styles.backBtn}>
          <Ionicons name="close" size={24} color={theme.text} />
        </TouchableOpacity>
        <Text style={[styles.appBarTitle, { color: theme.text }]}>Pagamento</Text>
      </View>

      <ScrollView contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false}>
        
        {/* Tonal Hero Area */}
        <Animated.View entering={FadeInUp.duration(600)} style={[styles.tonalHero, { backgroundColor: theme.primary + '08' }]}>
           <Text style={[styles.heroLabel, { color: theme.primary }]}>TOTAL A PAGAR</Text>
            <View style={styles.heroPriceRow}>
               <Text style={[styles.priceValue, { color: theme.text }]}>{amount}</Text>
            </View>
        </Animated.View>

        <View style={styles.body}>
          
          <View style={styles.sectionHeader}>
            <Text style={[styles.sectionTitle, { color: theme.text }]}>Método de Seleção</Text>
            <View style={styles.secureBadge}>
               <Ionicons name="shield-checkmark" size={14} color="#4caf50" />
               <Text style={styles.secureText}>Seguro</Text>
            </View>
          </View>

          {/* Clean Row Methods (No Cards) */}
          <View style={styles.methodsList}>
             <TouchableOpacity
                onPress={() => setSelectedMethod('cash')}
                style={[styles.methodRow, selectedMethod === 'cash' && { borderLeftColor: theme.primary }]}
             >
                <View style={[styles.methodIcon, { backgroundColor: selectedMethod === 'cash' ? theme.primary + '10' : 'rgba(0,0,0,0.03)' }]}>
                   <Ionicons name="cash-outline" size={22} color={selectedMethod === 'cash' ? theme.primary : theme.textMuted} />
                </View>
                <View style={styles.methodText}>
                   <Text style={[styles.methodTitle, { color: theme.text }]}>Dinheiro em Mão</Text>
                   <Text style={[styles.methodSub, { color: theme.textMuted }]}>Pague ao técnico no local</Text>
                </View>
                <View style={[styles.radio, { borderColor: selectedMethod === 'cash' ? theme.primary : '#DDD' }]}>
                   {selectedMethod === 'cash' && <View style={[styles.radioDot, { backgroundColor: theme.primary }]} />}
                </View>
             </TouchableOpacity>

             <TouchableOpacity
                onPress={() => setSelectedMethod('bank_transfer')}
                style={[styles.methodRow, selectedMethod === 'bank_transfer' && { borderLeftColor: theme.primary }]}
             >
                <View style={[styles.methodIcon, { backgroundColor: selectedMethod === 'bank_transfer' ? theme.primary + '10' : 'rgba(0,0,0,0.03)' }]}>
                   <Ionicons name="swap-horizontal-outline" size={22} color={selectedMethod === 'bank_transfer' ? theme.primary : theme.textMuted} />
                </View>
                <View style={styles.methodText}>
                   <Text style={[styles.methodTitle, { color: theme.text }]}>Transferência Bancária</Text>
                   <Text style={[styles.methodSub, { color: theme.textMuted }]}>Comprovativo necessário</Text>
                </View>
                <View style={[styles.radio, { borderColor: selectedMethod === 'bank_transfer' ? theme.primary : '#DDD' }]}>
                   {selectedMethod === 'bank_transfer' && <View style={[styles.radioDot, { backgroundColor: theme.primary }]} />}
                </View>
             </TouchableOpacity>
          </View>

          {/* Bank Flow - Tonal Area */}
          {selectedMethod === 'bank_transfer' && (
             <Animated.View entering={FadeInDown.duration(400)} style={styles.bankFlowArea}>
                <View style={[styles.bankInfoBlock, { backgroundColor: 'rgba(0,0,0,0.02)' }]}>
                   <Text style={[styles.infoLabel, { color: theme.textMuted }]}>DADOS DA CONTA</Text>
                   
                   <View style={styles.infoRow}>
                      <Text style={[styles.rowLabel, { color: theme.textMuted }]}>Banco</Text>
                      <Text style={[styles.rowValue, { color: theme.text }]}>{paymentInfo?.bankDetails?.bank_name || 'BCI - Moçambique'}</Text>
                   </View>
                   <View style={styles.infoRow}>
                      <Text style={[styles.rowLabel, { color: theme.textMuted }]}>Titular</Text>
                      <Text style={[styles.rowValue, { color: theme.text }]}>{paymentInfo?.bankDetails?.account_name || 'E-CABRAL SERVIÇOS'}</Text>
                   </View>
                   <View style={styles.infoRow}>
                      <Text style={[styles.rowLabel, { color: theme.textMuted }]}>IBAN</Text>
                      <Text style={[styles.rowValue, { color: theme.text }]}>{paymentInfo?.bankDetails?.account_number || '0000 0000 0000 0000'}</Text>
                   </View>
                </View>

                <View style={styles.uploadSection}>
                   <Text style={[styles.infoLabel, { color: theme.textMuted, marginBottom: 15 }]}>COMPROVATIVO</Text>
                   <TouchableOpacity
                      style={[styles.uploadBox, { borderColor: theme.border }]}
                      onPress={pickImage}
                   >
                      {receipt ? (
                         <View style={styles.receiptFrame}>
                            <Image source={{ uri: receipt.uri }} style={styles.receiptImg} />
                            <View style={styles.receiptSuccess}>
                               <Ionicons name="checkmark-circle" size={24} color="#FFF" />
                            </View>
                         </View>
                      ) : (
                         <View style={styles.uploadTrigger}>
                            <Ionicons name="camera-outline" size={28} color={theme.primary} />
                            <Text style={[styles.uploadText, { color: theme.primary }]}>Anexar Imagem</Text>
                         </View>
                      )}
                   </TouchableOpacity>
                </View>
             </Animated.View>
          )}

        </View>
      </ScrollView>

      {/* Bottom Bar - Pill style */}
      <View style={[styles.bottomBar, { borderTopColor: theme.border }]}>
         <TouchableOpacity
            style={[styles.pillBtn, { backgroundColor: theme.primary, opacity: loading || !selectedMethod ? 0.6 : 1 }]}
            onPress={handlePay}
            disabled={loading || !selectedMethod}
         >
            {loading ? (
               <ActivityIndicator color="#FFF" />
            ) : (
               <>
                  <Text style={styles.pillBtnText}>Finalizar Pagamento</Text>
                  <Ionicons name="arrow-forward" size={18} color="#FFF" style={{ marginLeft: 8 }} />
               </>
            )}
         </TouchableOpacity>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  loaderContainer: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  appBar: {
    height: 60,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    marginTop: Platform.OS === 'ios' ? 40 : 10,
  },
  backBtn: { padding: 8 },
  appBarTitle: { fontSize: 16, fontWeight: '800', marginLeft: 10 },
  scrollContent: { paddingBottom: 250 },

  // Hero
  tonalHero: {
    paddingVertical: 50,
    alignItems: 'center',
    gap: 8,
  },
  heroLabel: { fontSize: 9, fontWeight: '900', letterSpacing: 2 },
  heroPriceRow: { flexDirection: 'row', alignItems: 'baseline' },
  priceValue: { fontSize: 48, fontWeight: '900', letterSpacing: -1 },
  priceCurrency: { fontSize: 24, fontWeight: '700' },

  // Body
  body: { padding: 25 },
  sectionHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 30,
  },
  sectionTitle: { fontSize: 13, fontWeight: '900', textTransform: 'uppercase', letterSpacing: 1, opacity: 0.4 },
  secureBadge: { flexDirection: 'row', alignItems: 'center', gap: 4, opacity: 0.6 },
  secureText: { fontSize: 10, color: '#2E7D32', fontWeight: '900', textTransform: 'uppercase' },

  // Methods
  methodsList: { gap: 0 },
  methodRow: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 20,
    borderBottomWidth: 1,
    borderBottomColor: 'rgba(0,0,0,0.05)',
    gap: 16,
  },
  methodIcon: { width: 44, height: 44, borderRadius: 22, justifyContent: 'center', alignItems: 'center' },
  methodText: { flex: 1 },
  methodTitle: { fontSize: 15, fontWeight: '800' },
  methodSub: { fontSize: 12, marginTop: 2, fontWeight: '500', opacity: 0.5 },
  radio: { width: 22, height: 22, borderRadius: 11, borderWidth: 2, justifyContent: 'center', alignItems: 'center' },
  radioDot: { width: 10, height: 10, borderRadius: 5 },

  // Bank Area
  bankFlowArea: { marginTop: 30 },
  bankInfoBlock: { padding: 25, borderRadius: 20, gap: 12 },
  infoLabel: { fontSize: 9, fontWeight: '900', letterSpacing: 2, opacity: 0.5 },
  infoRow: { flexDirection: 'row', justifyContent: 'space-between', paddingVertical: 2 },
  rowLabel: { fontSize: 13, fontWeight: '600' },
  rowValue: { fontSize: 14, fontWeight: '900' },
  
  uploadSection: { marginTop: 35 },
  uploadBox: { height: 120, borderRadius: 20, borderWidth: 1.5, borderStyle: 'dashed', justifyContent: 'center', alignItems: 'center', overflow: 'hidden' },
  uploadTrigger: { alignItems: 'center', gap: 8 },
  uploadText: { fontSize: 12, fontWeight: '800' },
  receiptFrame: { width: '100%', height: '100%' },
  receiptImg: { width: '100%', height: '100%' },
  receiptSuccess: { ...StyleSheet.absoluteFillObject, backgroundColor: 'rgba(0,0,0,0.3)', justifyContent: 'center', alignItems: 'center' },

  // Bottom Bar
  bottomBar: {
    position: 'absolute',
    bottom: 0, left: 0, right: 0,
    padding: 24, paddingBottom: Platform.OS === 'ios' ? 125 : 110, // Increased by 15% as requested for perfect clearance
    backgroundColor: '#FFF', borderTopWidth: 1,
  },
  pillBtn: { height: 60, borderRadius: 30, flexDirection: 'row', alignItems: 'center', justifyContent: 'center' },
  pillBtnText: { color: '#FFF', fontSize: 16, fontWeight: '900' }
});
