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: any) {
      const errorMessage = err.message || '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-indigo-600" />
        <span className="ml-2 text-gray-600">Loading payment form...</span>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      <div className="bg-white rounded-lg border border-gray-200 p-6">
        <div className="flex items-center gap-2 mb-4">
          <CreditCard className="w-5 h-5 text-indigo-600" />
          <h3 className="text-lg font-semibold text-gray-900">
            Payment Details
          </h3>
        </div>
        
        <div className="mb-4 p-4 bg-indigo-50 border border-indigo-200 rounded-lg">
          <div className="flex justify-between items-center">
            <span className="text-sm font-medium text-indigo-900">
              Amount to Pay
            </span>
            <span className="text-xl font-bold text-indigo-600">
              ${amount.toFixed(2)}
            </span>
          </div>
        </div>

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

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

        <button
          type="submit"
          disabled={isProcessing || !stripe || !elements}
          className="w-full bg-indigo-600 text-white py-3 px-4 rounded-lg 
            hover:bg-indigo-700 transition-colors font-semibold 
            disabled:bg-gray-400 disabled:cursor-not-allowed
            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>

        <p className="text-xs text-gray-500 mt-3 text-center">
          Your payment is secure and encrypted
        </p>
      </div>
    </form>
  );
};

export default StripePaymentForm;

