import React, { useState } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  ScrollView,
  ActivityIndicator,
  Alert,
} from 'react-native';
import { useRouter, useLocalSearchParams } from 'expo-router';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useLanguage } from '@/i18n/LanguageContext';
import { useTheme } from '@/constants/ThemeContext';
import { bookingStyles } from '@/styles/booking.styles';
import { ArrowLeft, CheckCircle2, ShieldCheck, Smartphone, CreditCard, AlertCircle } from 'lucide-react-native';
import { BookingApi } from '@/services/api';
import AsyncStorage from '@react-native-async-storage/async-storage';

export default function PaymentBookingScreen() {
  const router = useRouter();
  const params = useLocalSearchParams();
  const { t } = useLanguage();
  const { isDark } = useTheme();

  const tripId = (params.tripId as string) || '';
  const routeName = (params.route as string) || 'Bamenda to Buea';
  const agencyName = (params.agencyName as string) || 'Garanti Express';
  const selectedSeats = (params.selectedSeats as string) || '';
  const selectedSeatIds = (params.selectedSeatIds as string) || '';
  const totalPrice = (params.totalPrice as string) || '0';
  const fullName = (params.fullName as string) || 'Jean Perrin';
  const defaultPhone = (params.phoneNumber as string) || '+237 670 000 000';
  const idCardNumber = (params.idCardNumber as string) || '';

  const [paymentMethod, setPaymentMethod] = useState<'MTN_MOMO' | 'ORANGE_MONEY' | 'CARD'>('MTN_MOMO');
  const [momoNumber, setMomoNumber] = useState(defaultPhone);
  const [isProcessing, setIsProcessing] = useState(false);
  const [isVerifying, setIsVerifying] = useState(false);
  const [createdBookingRef, setCreatedBookingRef] = useState<string | null>(null);
  const [ussdCode, setUssdCode] = useState<string | null>(null);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  const handleInitiatePayment = async () => {
    setIsProcessing(true);
    setErrorMessage(null);

    try {
      // 1. Resolve seat ID and number
      let seatIdsList: string[] = [];
      try {
        if (selectedSeatIds) {
          const parsed = JSON.parse(selectedSeatIds);
          if (Array.isArray(parsed)) seatIdsList = parsed.map(String);
        }
      } catch (_) {
        if (selectedSeatIds) seatIdsList = selectedSeatIds.split(',').map((s) => s.trim());
      }

      const seatNumberList = selectedSeats ? selectedSeats.split(',').map((s) => s.trim()) : ['1'];
      const rawSeatId = seatIdsList[0] || seatNumberList[0] || '1';
      const cleanSeatId = rawSeatId.replace(/^seat-/, '');
      const numericSeatId = parseInt(cleanSeatId, 10) || 1;

      const numericTripId = parseInt(tripId.replace(/^trip-/, ''), 10) || 8;
      const cleanAmount = parseInt(totalPrice.replace(/[^0-9]/g, ''), 10) || 6500;

      // Validate & format phone number
      const rawPhone = momoNumber || defaultPhone;
      const digitsOnly = rawPhone.replace(/[^0-9]/g, '');
      const localPhone = digitsOnly.startsWith('237') ? digitsOnly.slice(3) : digitsOnly;
      if (localPhone.length < 9) {
        throw new Error('Please enter a valid 9-digit Cameroon phone number (e.g. 677 777 777).');
      }
      const formattedPhone = '237' + localPhone.slice(-9);

      // 2. Submit booking request to backend API (POST /api/bookings)
      const bookingPayload = {
        trip_id: numericTripId,
        seat_id: numericSeatId,
        seat_number: seatNumberList[0],
        passenger_name: fullName,
        passenger_phone: formattedPhone,
        passenger_cni: idCardNumber,
        payment_method: paymentMethod.toLowerCase(),
        total_amount: cleanAmount,
      };

      const bookingResult = await BookingApi.createBooking(bookingPayload);
      const bookingRef =
        bookingResult?.booking_ref ||
        bookingResult?.booking?.booking_ref ||
        bookingResult?.data?.booking_ref;

      if (!bookingRef) {
        throw new Error('Failed to retrieve booking reference from server.');
      }

      const code =
        bookingResult?.payment_instructions?.ussd_code ||
        bookingResult?.data?.payment_instructions?.ussd_code ||
        (paymentMethod === 'MTN_MOMO' ? '*126#' : '#150*50#');

      setCreatedBookingRef(bookingRef);
      setUssdCode(code);
    } catch (err: any) {
      console.error('Booking submission error:', err);
      const msg = err?.message || 'Failed to submit booking request. Please check your network and try again.';
      setErrorMessage(msg);
      Alert.alert('Booking Error', msg);
    } finally {
      setIsProcessing(false);
    }
  };

  const handleConfirmPayment = async () => {
    if (!createdBookingRef) return;
    setIsVerifying(true);
    setErrorMessage(null);

    try {
      const confirmResult = await BookingApi.confirmBooking(createdBookingRef);
      const ticketNumber =
        confirmResult?.ticket?.ticket_number ||
        confirmResult?.data?.ticket?.ticket_number ||
        '';

      try {
        const rawPhone = momoNumber || defaultPhone;
        const cleanPhone = rawPhone.replace(/[^0-9]/g, '');
        if (cleanPhone) {
          await AsyncStorage.setItem('@travelcam_passenger_phone', cleanPhone);
        }
        if (ticketNumber) {
          const existing = await AsyncStorage.getItem('@travelcam_ticket_numbers');
          const list = existing ? JSON.parse(existing) : [];
          if (!list.includes(ticketNumber)) {
            list.unshift(ticketNumber);
            await AsyncStorage.setItem('@travelcam_ticket_numbers', JSON.stringify(list));
          }
        }
      } catch (_) {}

      router.push({
        pathname: '/booking/confirmation',
        params: {
          bookingRef: createdBookingRef,
          ticketNumber,
          route: routeName,
          agencyName,
          selectedSeats,
          totalPrice,
          fullName,
          paymentMethod,
        },
      } as any);
    } catch (confirmErr: any) {
      console.warn('Payment verification pending or error:', confirmErr);
      const msg =
        confirmErr?.message ||
        'Payment has not been completed yet. Please approve the USSD prompt on your phone and try again.';
      setErrorMessage(msg);
      Alert.alert('Payment Pending', msg);
    } finally {
      setIsVerifying(false);
    }
  };

  return (
    <SafeAreaView
      edges={['top', 'left', 'right']}
      style={[
        bookingStyles.container,
        { backgroundColor: isDark ? '#071126' : '#F8FAFC' },
      ]}
    >
      <ScrollView
        showsVerticalScrollIndicator={false}
        contentContainerStyle={bookingStyles.scrollContent}
      >
        <TouchableOpacity
          onPress={() => router.back()}
          style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 12 }}
        >
          <ArrowLeft size={20} color={isDark ? '#F8FAFC' : '#0B1F4D'} />
          <Text style={{ fontSize: 16, fontWeight: '800', color: isDark ? '#F8FAFC' : '#0B1F4D', marginLeft: 8 }}>
            Back to Passenger Info
          </Text>
        </TouchableOpacity>

        <Text style={isDark ? bookingStyles.headerTitleDark : bookingStyles.headerTitleLight}>
          Payment Checkout
        </Text>
        <Text style={isDark ? bookingStyles.headerSubtitleDark : bookingStyles.headerSubtitleLight}>
          Select your payment provider & authorize mobile money checkout
        </Text>

        {/* Amount Summary Card */}
        <View
          style={[
            bookingStyles.summaryCard,
            isDark ? bookingStyles.summaryCardDark : bookingStyles.summaryCardLight,
            { backgroundColor: isDark ? '#0F172A' : '#EFF6FF', borderColor: '#38BDF8' },
          ]}
        >
          <Text style={{ fontSize: 13, fontWeight: '700', color: '#64748B', marginBottom: 4 }}>
            Amount Due
          </Text>
          <Text style={{ fontSize: 26, fontWeight: '900', color: isDark ? '#38BDF8' : '#0B1F4D' }}>
            {totalPrice} FCFA
          </Text>
          <Text style={{ fontSize: 12, fontWeight: '600', color: '#15803D', marginTop: 4 }}>
            {routeName} • {selectedSeats ? `Seat ${selectedSeats}` : 'No seat selected'} ({fullName})
          </Text>
        </View>

        {/* Payment Methods */}
        <Text style={[isDark ? bookingStyles.fieldLabelDark : bookingStyles.fieldLabelLight, { fontSize: 15, marginBottom: 10 }]}>
          Select Payment Provider
        </Text>

        {/* MTN Mobile Money Option */}
        <TouchableOpacity
          onPress={() => setPaymentMethod('MTN_MOMO')}
          activeOpacity={0.8}
          style={[
            bookingStyles.paymentOptionCard,
            paymentMethod === 'MTN_MOMO'
              ? isDark
                ? bookingStyles.paymentOptionCardSelectedDark
                : bookingStyles.paymentOptionCardSelected
              : isDark
              ? bookingStyles.paymentOptionCardUnselectedDark
              : bookingStyles.paymentOptionCardUnselectedLight,
          ]}
        >
          <View style={bookingStyles.paymentBrandRow}>
            <View style={[bookingStyles.momoLogoBadge, { backgroundColor: '#FFCC00' }]}>
              <Text style={{ fontWeight: '900', fontSize: 11, color: '#000000' }}>MoMo</Text>
            </View>
            <View>
              <Text style={isDark ? bookingStyles.momoTextNameDark : bookingStyles.momoTextNameLight}>
                MTN Mobile Money
              </Text>
              <Text style={{ fontSize: 11, fontWeight: '600', color: '#64748B' }}>
                Instant USSD push authorization
              </Text>
            </View>
          </View>
          {paymentMethod === 'MTN_MOMO' && <CheckCircle2 size={22} color="#15803D" />}
        </TouchableOpacity>

        {/* Orange Money Option */}
        <TouchableOpacity
          onPress={() => setPaymentMethod('ORANGE_MONEY')}
          activeOpacity={0.8}
          style={[
            bookingStyles.paymentOptionCard,
            paymentMethod === 'ORANGE_MONEY'
              ? isDark
                ? bookingStyles.paymentOptionCardSelectedDark
                : bookingStyles.paymentOptionCardSelected
              : isDark
              ? bookingStyles.paymentOptionCardUnselectedDark
              : bookingStyles.paymentOptionCardUnselectedLight,
          ]}
        >
          <View style={bookingStyles.paymentBrandRow}>
            <View style={[bookingStyles.momoLogoBadge, { backgroundColor: '#FF6600' }]}>
              <Text style={{ fontWeight: '900', fontSize: 11, color: '#FFFFFF' }}>OM</Text>
            </View>
            <View>
              <Text style={isDark ? bookingStyles.momoTextNameDark : bookingStyles.momoTextNameLight}>
                Orange Money
              </Text>
              <Text style={{ fontSize: 11, fontWeight: '600', color: '#64748B' }}>
                Instant mobile wallet debit
              </Text>
            </View>
          </View>
          {paymentMethod === 'ORANGE_MONEY' && <CheckCircle2 size={22} color="#15803D" />}
        </TouchableOpacity>

        {/* Credit Card Option */}
        <TouchableOpacity
          onPress={() => setPaymentMethod('CARD')}
          activeOpacity={0.8}
          style={[
            bookingStyles.paymentOptionCard,
            paymentMethod === 'CARD'
              ? isDark
                ? bookingStyles.paymentOptionCardSelectedDark
                : bookingStyles.paymentOptionCardSelected
              : isDark
              ? bookingStyles.paymentOptionCardUnselectedDark
              : bookingStyles.paymentOptionCardUnselectedLight,
          ]}
        >
          <View style={bookingStyles.paymentBrandRow}>
            <View style={[bookingStyles.momoLogoBadge, { backgroundColor: '#1E3A8A' }]}>
              <CreditCard size={18} color="#FFFFFF" />
            </View>
            <View>
              <Text style={isDark ? bookingStyles.momoTextNameDark : bookingStyles.momoTextNameLight}>
                Bank Card (Visa / Mastercard)
              </Text>
              <Text style={{ fontSize: 11, fontWeight: '600', color: '#64748B' }}>
                Secure 2FA bank card gateway
              </Text>
            </View>
          </View>
          {paymentMethod === 'CARD' && <CheckCircle2 size={22} color="#15803D" />}
        </TouchableOpacity>

        {/* Payment Account Input */}
        {(paymentMethod === 'MTN_MOMO' || paymentMethod === 'ORANGE_MONEY') && (
          <View style={[bookingStyles.inputGroup, { marginTop: 10 }]}>
            <Text style={isDark ? bookingStyles.fieldLabelDark : bookingStyles.fieldLabelLight}>
              {paymentMethod === 'MTN_MOMO' ? 'MTN MoMo Number' : 'Orange Money Number'}
            </Text>
            <TextInput
              value={momoNumber}
              onChangeText={setMomoNumber}
              placeholder="+237 6XX XXX XXX"
              keyboardType="phone-pad"
              placeholderTextColor="#94A3B8"
              editable={!createdBookingRef}
              style={[
                bookingStyles.textInput,
                isDark ? bookingStyles.textInputDark : bookingStyles.textInputLight,
              ]}
            />
            {/* Quick Demo Numbers helper */}
            {!createdBookingRef && (
              <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 6, flexWrap: 'wrap' }}>
                <Text style={{ fontSize: 11, color: '#64748B' }}>Demo test numbers: </Text>
                <TouchableOpacity onPress={() => setMomoNumber('677777777')}>
                  <Text style={{ fontSize: 11, fontWeight: '800', color: '#0284C7', marginRight: 10 }}>
                    MTN (677777777)
                  </Text>
                </TouchableOpacity>
                <TouchableOpacity onPress={() => setMomoNumber('699999999')}>
                  <Text style={{ fontSize: 11, fontWeight: '800', color: '#EA580C' }}>
                    Orange (699999999)
                  </Text>
                </TouchableOpacity>
              </View>
            )}
          </View>
        )}

        {/* Security badge */}
        <View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 8, marginBottom: 16 }}>
          <ShieldCheck size={16} color="#15803D" />
          <Text style={{ fontSize: 12, fontWeight: '600', color: '#15803D', marginLeft: 6 }}>
            256-bit Encrypted & Authorized by Cameroon Mobile Money System
          </Text>
        </View>

        {/* Error Feedback Banner */}
        {errorMessage && (
          <View
            style={{
              backgroundColor: '#FEE2E2',
              borderWidth: 1,
              borderColor: '#EF4444',
              borderRadius: 8,
              padding: 12,
              marginBottom: 16,
              flexDirection: 'row',
              alignItems: 'center',
            }}
          >
            <AlertCircle size={20} color="#DC2626" style={{ marginRight: 8 }} />
            <Text style={{ flex: 1, color: '#991B1B', fontSize: 13, fontWeight: '600' }}>
              {errorMessage}
            </Text>
          </View>
        )}

        {/* Awaiting Payment Verification Card */}
        {createdBookingRef ? (
          <View
            style={{
              backgroundColor: isDark ? '#1E293B' : '#FEF3C7',
              borderWidth: 1.5,
              borderColor: '#F59E0B',
              borderRadius: 12,
              padding: 16,
              marginBottom: 16,
            }}
          >
            <View style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 8 }}>
              <Smartphone size={22} color="#D97706" style={{ marginRight: 8 }} />
              <Text style={{ fontSize: 16, fontWeight: '900', color: isDark ? '#FDE68A' : '#92400E' }}>
                Payment Prompt Sent!
              </Text>
            </View>

            <Text style={{ fontSize: 13, color: isDark ? '#CBD5E1' : '#78350F', lineHeight: 19, marginBottom: 10 }}>
              A payment request of <Text style={{ fontWeight: '800' }}>{totalPrice} FCFA</Text> has been sent to <Text style={{ fontWeight: '800' }}>{momoNumber}</Text>.
              {'\n'}Please check your phone, enter your Mobile Money PIN, or dial <Text style={{ fontWeight: '900', color: '#D97706' }}>{ussdCode || '*126#'}</Text> to approve.
            </Text>

            <View style={{ backgroundColor: isDark ? '#0F172A' : '#FFFBEB', padding: 8, borderRadius: 6, marginBottom: 14 }}>
              <Text style={{ fontSize: 12, fontWeight: '700', color: isDark ? '#94A3B8' : '#B45309' }}>
                Booking Ref: <Text style={{ fontWeight: '900', color: isDark ? '#38BDF8' : '#0B1F4D' }}>{createdBookingRef}</Text>
              </Text>
            </View>

            <TouchableOpacity
              onPress={handleConfirmPayment}
              disabled={isVerifying}
              style={[bookingStyles.primaryBtn, { backgroundColor: '#15803D' }]}
            >
              {isVerifying ? (
                <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                  <ActivityIndicator color="#FFFFFF" style={{ marginRight: 8 }} />
                  <Text style={bookingStyles.primaryBtnText}>Verifying Payment Status...</Text>
                </View>
              ) : (
                <Text style={bookingStyles.primaryBtnText}>
                  I Have Approved Payment
                </Text>
              )}
            </TouchableOpacity>

            <TouchableOpacity
              onPress={() => {
                setCreatedBookingRef(null);
                setErrorMessage(null);
              }}
              disabled={isVerifying}
              style={{ marginTop: 12, alignItems: 'center', paddingVertical: 6 }}
            >
              <Text style={{ fontSize: 13, fontWeight: '700', color: isDark ? '#94A3B8' : '#64748B' }}>
                Change Phone Number or Retry
              </Text>
            </TouchableOpacity>
          </View>
        ) : (
          <TouchableOpacity
            onPress={handleInitiatePayment}
            disabled={isProcessing}
            style={bookingStyles.primaryBtn}
          >
            {isProcessing ? (
              <ActivityIndicator color="#FFFFFF" />
            ) : (
              <Text style={bookingStyles.primaryBtnText}>
                Initiate Payment ({totalPrice} FCFA)
              </Text>
            )}
          </TouchableOpacity>
        )}
      </ScrollView>
    </SafeAreaView>
  );
}
