// components/checkout/StripePaymentForm.tsx
'use client';

import { useState } from 'react';
import { PaymentElement, useStripe, useElements } from '@stripe/react-stripe-js';
import { useRouter } from 'next/navigation';
import { Lock, Loader2, AlertCircle, CheckCircle } from 'lucide-react';

interface StripePaymentFormProps {
  orderNumber: string;
  paymentIntentId: string;
  total: number;
  // ✅ No onSuccess prop — cart is cleared on the success page instead
}

export default function StripePaymentForm({
  orderNumber,
  paymentIntentId,
  total,
}: StripePaymentFormProps) {
  const stripe = useStripe();
  const elements = useElements();
  const router = useRouter();

  const [isProcessing, setIsProcessing] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');
  const [isReady, setIsReady] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!stripe || !elements) return;

    setIsProcessing(true);
    setErrorMessage('');

    try {
      // Step 1: Confirm payment with Stripe (handles 3DS, card validation, etc.)
      const { error: stripeError, paymentIntent } = await stripe.confirmPayment({
        elements,
        redirect: 'if_required',
      });

      if (stripeError) {
        setErrorMessage(
          stripeError.type === 'card_error' || stripeError.type === 'validation_error'
            ? stripeError.message || 'Card was declined. Please check your details.'
            : 'An unexpected error occurred. Please try again.'
        );
        setIsProcessing(false);
        return;
      }

      if (!paymentIntent || paymentIntent.status !== 'succeeded') {
        setErrorMessage('Payment was not completed. Please try again.');
        setIsProcessing(false);
        return;
      }

      // Step 2: Confirm with our server & update DB
      const response = await fetch('/api/frontend/checkout/stripe/confirm-payment', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          paymentIntentId: paymentIntent.id,
          orderNumber,
        }),
      });

      const data = await response.json();

      if (!data.success) {
        setErrorMessage(data.error || 'Payment confirmed but order update failed. Please contact support.');
        setIsProcessing(false);
        return;
      }

      // Step 3: Redirect to success page — cart is cleared THERE, not here
      router.replace(`/checkout/success?orderNumber=${orderNumber}&clearCart=true`);

    } catch (err) {
      console.error('Stripe payment error:', err);
      setErrorMessage('Network error. Please check your connection and try again.');
      setIsProcessing(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {/* Stripe PaymentElement */}
      <div className={`transition-opacity duration-300 ${isReady ? 'opacity-100' : 'opacity-0'}`}>
        <PaymentElement
          onReady={() => setIsReady(true)}
          options={{
            layout: 'tabs',
            paymentMethodOrder: ['card', 'apple_pay', 'google_pay'],
          }}
        />
      </div>

      {/* Loading skeleton */}
      {!isReady && (
        <div className="space-y-3 animate-pulse">
          <div className="h-12 bg-slate-100 rounded-xl" />
          <div className="grid grid-cols-2 gap-3">
            <div className="h-12 bg-slate-100 rounded-xl" />
            <div className="h-12 bg-slate-100 rounded-xl" />
          </div>
        </div>
      )}

      {/* Error */}
      {errorMessage && (
        <div className="flex items-start gap-3 p-4 bg-rose-50 border border-rose-200 rounded-xl">
          <AlertCircle className="h-5 w-5 text-rose-500 shrink-0 mt-0.5" />
          <p className="text-rose-700 text-sm">{errorMessage}</p>
        </div>
      )}

      {/* Security note */}
      <div className="flex items-center gap-2 text-xs text-slate-500 bg-slate-50 px-4 py-3 rounded-xl border border-slate-200">
        <CheckCircle className="h-4 w-4 text-emerald-500 shrink-0" />
        <span>
          Your payment info is encrypted and processed securely by{' '}
          <span className="font-semibold text-slate-700">Stripe</span>. We never store your card details.
        </span>
      </div>

      {/* Pay Button */}
      <button
        type="submit"
        disabled={!stripe || !elements || isProcessing || !isReady}
        className="w-full flex items-center justify-center gap-3 bg-gradient-to-r from-violet-600 to-indigo-600 hover:from-violet-700 hover:to-indigo-700 text-white py-4 rounded-xl font-semibold shadow-lg hover:shadow-xl transition-all duration-300 transform hover:scale-[1.01] disabled:opacity-60 disabled:cursor-not-allowed disabled:transform-none"
      >
        {isProcessing ? (
          <>
            <Loader2 className="h-5 w-5 animate-spin" />
            <span>Processing Payment...</span>
          </>
        ) : (
          <>
            <Lock className="h-5 w-5" />
            <span>
              Pay ${total.toLocaleString('en-US', { minimumFractionDigits: 2 })} Securely
            </span>
          </>
        )}
      </button>
    </form>
  );
}