import React, { useState, useEffect } from 'react';
import {
  PaymentElement,
  useStripe,
  useElements,
} from '@stripe/react-stripe-js';
import { CreditCard, Loader2, AlertCircle, CheckCircle } from 'lucide-react';
import { toast } from 'react-toastify';

interface StripePaymentFormProps {
  clientSecret: string;
  amount: number;
  onSuccess: (paymentIntentId: string) => void;
  onError: (error: string) => void;
}

const StripePaymentForm: React.FC<StripePaymentFormProps> = ({
  clientSecret,
  amount,
  onSuccess,
  onError,
}) => {
  const stripe = useStripe();
  const elements = useElements();
  
  const [isProcessing, setIsProcessing] = useState(false);
  const [message, setMessage] = useState<string | null>(null);

  useEffect(() => {
    if (!stripe || !clientSecret) {
      return;
    }
  }, [stripe, clientSecret]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!stripe || !elements) {
      return;
    }

    setIsProcessing(true);
    setMessage(null);

    try {
      const { error, paymentIntent } = await stripe.confirmPayment({
        elements,
        confirmParams: {
          return_url: window.location.origin + '/payment-success',
        },
        redirect: 'if_required',
      });

      if (error) {
        setMessage(error.message || 'An error occurred during payment');
        onError(error.message || 'Payment failed');
        toast.error(error.message || 'Payment failed');
      } else if (paymentIntent && paymentIntent.status === 'succeeded') {
        setMessage('Payment succeeded!');
        toast.success('Payment successful!');
        onSuccess(paymentIntent.id);
      } else {
        setMessage('Payment processing...');
      }
    } catch (err: unknown) {
      const errorMessage = getUserFriendlyError(err) || 'An unexpected error occurred';
      setMessage(errorMessage);
      onError(errorMessage);
      toast.error(errorMessage);
    } finally {
      setIsProcessing(false);
    }
  };

  if (!stripe || !elements) {
    return (
      <div className="flex items-center justify-center p-8">
        <Loader2 className="w-8 h-8 animate-spin text-[var(--luxury-gold)]" />
        <span className="ml-2 text-gray-300">Loading payment form...</span>
      </div>
    );
  }

  return (
    <form 
      onSubmit={handleSubmit} 
      className="space-y-4"
      autoComplete="off"
      // SECURITY: Prevent form caching and autocomplete for payment forms
    >
      <div className="mb-4 p-4 bg-[var(--luxury-gold)]/10 border border-[var(--luxury-gold)]/20 rounded-lg">
        <div className="flex justify-between items-center">
          <span className="text-sm font-medium text-gray-300">
            Amount to Pay
          </span>
          <span className="text-xl font-bold text-[var(--luxury-gold)]">
            ${amount.toFixed(2)}
          </span>
        </div>
      </div>

      <div className="mb-4">
        <PaymentElement
          options={{
            layout: 'tabs',
          }}
        />
      </div>

      {message && (
        <div
          className={`mb-4 p-3 rounded-lg flex items-start gap-3 ${
            message.includes('succeeded')
              ? 'bg-green-500/10 border border-green-500/30'
              : message.includes('error') || message.includes('failed')
              ? 'bg-red-500/10 border border-red-500/30'
              : 'bg-yellow-500/10 border border-yellow-500/30'
          }`}
        >
          {message.includes('succeeded') ? (
            <CheckCircle className="w-5 h-5 text-green-400 mt-0.5 flex-shrink-0" />
          ) : message.includes('error') || message.includes('failed') ? (
            <AlertCircle className="w-5 h-5 text-red-400 mt-0.5 flex-shrink-0" />
          ) : (
            <Loader2 className="w-5 h-5 text-yellow-400 mt-0.5 animate-spin flex-shrink-0" />
          )}
          <p
            className={`text-sm ${
              message.includes('succeeded')
                ? 'text-green-300'
                : message.includes('error') || message.includes('failed')
                ? 'text-red-300'
                : 'text-yellow-300'
            }`}
          >
            {message}
          </p>
        </div>
      )}

      <button
        type="submit"
        disabled={isProcessing || !stripe || !elements}
        className="w-full bg-[var(--luxury-gold)] text-black py-3 px-4 rounded-lg 
          hover:bg-[var(--luxury-gold-dark)] transition-colors font-semibold 
          disabled:bg-gray-600 disabled:cursor-not-allowed disabled:text-gray-400
          flex items-center justify-center gap-2"
      >
        {isProcessing ? (
          <>
            <Loader2 className="w-5 h-5 animate-spin" />
            Processing...
          </>
        ) : (
          <>
            <CreditCard className="w-5 h-5" />
            Pay ${amount.toFixed(2)}
          </>
        )}
      </button>

      <div className="mt-4 space-y-2">
        <p className="text-xs text-gray-500 text-center">
          Your payment is secure and encrypted
        </p>
        <div className="flex items-center justify-center gap-3 text-xs text-gray-400">
          <span className="flex items-center gap-1">
            <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z" clipRule="evenodd" />
            </svg>
            PCI DSS Compliant
          </span>
          <span className="text-gray-600">•</span>
          <span>Powered by Stripe</span>
        </div>
      </div>
    </form>
  );
};

export default StripePaymentForm;

