import React, { useState, useEffect } from 'react';
import { loadStripe, StripeElementsOptions } from '@stripe/stripe-js';
import { Elements } from '@stripe/react-stripe-js';
import StripePaymentForm from './StripePaymentForm';
import { createStripePaymentIntent, confirmStripePayment } from '../services/paymentService';
import { X, Loader2, AlertCircle } from 'lucide-react';
import { toast } from 'react-toastify';

interface StripePaymentModalProps {
  isOpen: boolean;
  bookingId: number;
  amount: number;
  currency?: string;
  onSuccess: () => void;
  onClose: () => void;
}

const StripePaymentModal: React.FC<StripePaymentModalProps> = ({
  isOpen,
  bookingId,
  amount,
  currency = 'usd',
  onSuccess,
  onClose,
}) => {
  const [stripePromise, setStripePromise] = useState<Promise<unknown> | null>(null);
  const [clientSecret, setClientSecret] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [paymentCompleted, setPaymentCompleted] = useState(false);

  useEffect(() => {
    if (!isOpen || paymentCompleted) return;

    const initializeStripe = async () => {
      try {
        setLoading(true);
        setError(null);

        const response = await createStripePaymentIntent(
          bookingId,
          amount,
          currency
        );

        if (response.success && response.data) {
          const { publishable_key, client_secret } = response.data;
          
          if (!client_secret) {
            throw new Error('Client secret not received from server');
          }
          
          if (!publishable_key) {
            throw new Error('Publishable key not configured. Please configure Stripe settings in Admin Panel.');
          }
          
          setClientSecret(client_secret);
          const stripePromise = loadStripe(publishable_key);
          setStripePromise(stripePromise);
        } else {
          throw new Error(response.message || 'Failed to initialize payment');
        }
      } catch (err: unknown) {
        console.error('Error initializing Stripe:', err);
        const errorMessage = getUserFriendlyError(err) || getUserFriendlyError(err) || 'Failed to initialize payment';
        setError(errorMessage);
        toast.error(errorMessage);
      } finally {
        setLoading(false);
      }
    };

    initializeStripe();
  }, [isOpen, bookingId, amount, currency, paymentCompleted]);

  const handlePaymentSuccess = async (paymentIntentId: string) => {
    try {
      setPaymentCompleted(true);
      const response = await confirmStripePayment(paymentIntentId, bookingId);
      
      if (response.success) {
        toast.success('✅ Payment successful!');
        onSuccess();
      } else {
        setPaymentCompleted(false);
        throw new Error(response.message || 'Payment confirmation failed');
      }
    } catch (err: unknown) {
      console.error('Error confirming payment:', err);
      setPaymentCompleted(false);
      const errorMessage = getUserFriendlyError(err) || getUserFriendlyError(err) || 'Payment confirmation failed';
      setError(errorMessage);
      toast.error(errorMessage);
    }
  };

  const handlePaymentError = (errorMessage: string) => {
    setError(errorMessage);
    toast.error(errorMessage);
  };

  if (!isOpen) return null;

  const options: StripeElementsOptions = {
    clientSecret: clientSecret || undefined,
    appearance: {
      theme: 'night' as const,
      variables: {
        colorPrimary: '#d4af37',
        colorBackground: '#0a0a0a',
        colorText: '#ffffff',
        colorDanger: '#ef4444',
        fontFamily: 'system-ui, sans-serif',
        spacingUnit: '4px',
        borderRadius: '8px',
      },
    },
  };

  return (
    <div className="fixed inset-0 z-[10000] flex items-center justify-center p-2 sm:p-4">
      <div
        className="fixed inset-0 bg-black/90 backdrop-blur-sm"
        onClick={onClose}
      />
      <div className="relative w-full max-w-md max-h-[95vh] bg-gradient-to-br from-[#0a0a0a] via-[#1a1a1a] to-[#0a0a0a] rounded-xl sm:rounded-2xl border border-[var(--luxury-gold)]/30 shadow-2xl shadow-[var(--luxury-gold)]/20 overflow-hidden flex flex-col">
        {/* Header */}
        <div className="px-3 sm:px-4 md:px-6 py-3 sm:py-4 border-b border-[var(--luxury-gold)]/20 bg-gradient-to-r from-[#1a1a1a] to-[#0a0a0a] flex-shrink-0">
          <div className="flex items-center justify-between gap-2">
            <h2 className="text-base sm:text-lg md:text-xl font-serif font-bold text-white tracking-tight truncate flex-1">
              Complete Payment
            </h2>
            <button
              onClick={onClose}
              className="p-1.5 sm:p-2 hover:bg-[var(--luxury-gold)]/10 rounded-lg transition-colors text-gray-400 hover:text-white flex-shrink-0"
            >
              <X className="w-4 h-4 sm:w-5 sm:h-5" />
            </button>
          </div>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-3 sm:p-4 md:p-6">
          {loading ? (
            <div className="flex flex-col items-center justify-center py-8 sm:py-12">
              <Loader2 className="w-10 h-10 sm:w-12 sm:h-12 animate-spin text-[var(--luxury-gold)] mb-3 sm:mb-4" />
              <p className="text-xs sm:text-sm text-gray-400">Initializing payment...</p>
            </div>
          ) : error ? (
            <div className="bg-red-500/10 border border-red-500/30 rounded-lg p-3 sm:p-4">
              <div className="flex items-start gap-2 sm:gap-3">
                <AlertCircle className="w-4 h-4 sm:w-5 sm:h-5 text-red-400 mt-0.5 flex-shrink-0" />
                <div className="min-w-0 flex-1">
                  <h3 className="text-xs sm:text-sm font-semibold text-red-300 mb-1">
                    Payment Initialization Failed
                  </h3>
                  <p className="text-xs text-red-200/80 leading-relaxed">
                    {error || 'Unable to initialize payment. Please try again.'}
                  </p>
                </div>
              </div>
            </div>
          ) : clientSecret && stripePromise ? (
            <Elements stripe={stripePromise} options={options}>
              <StripePaymentForm
                clientSecret={clientSecret}
                amount={amount}
                onSuccess={handlePaymentSuccess}
                onError={handlePaymentError}
              />
            </Elements>
          ) : (
            <div className="flex flex-col items-center justify-center py-8 sm:py-12">
              <Loader2 className="w-10 h-10 sm:w-12 sm:h-12 animate-spin text-[var(--luxury-gold)] mb-3 sm:mb-4" />
              <p className="text-xs sm:text-sm text-gray-400">Loading payment form...</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default StripePaymentModal;

