// app/checkout/paypal/capture/PayPalCaptureContent.tsx
'use client';

import { useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { motion } from 'framer-motion';
import { CheckCircle, XCircle, Loader2 } from 'lucide-react';

type Status = 'processing' | 'success' | 'error';

export function PayPalCaptureContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [status, setStatus] = useState<Status>('processing');
  const [errorMessage, setErrorMessage] = useState('');

  useEffect(() => {
    const capturePayment = async () => {
      // PayPal appends ?token=PAYPAL_ORDER_ID to the return URL
      const paypalOrderId = searchParams.get('token');
      const orderNumber = searchParams.get('orderNumber');

      if (!paypalOrderId || !orderNumber) {
        setStatus('error');
        setErrorMessage('Missing payment information. Please contact support.');
        return;
      }

      try {
        const response = await fetch('/api/frontend/checkout/paypal/capture-order', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ paypalOrderId, orderNumber }),
        });

        const data = await response.json();

        if (data.success) {
          setStatus('success');
          // Clear the cart from Zustand (we pass the signal via URL)
          // Redirect to success page with order details
          setTimeout(() => {
            router.replace(`/checkout/success?orderNumber=${orderNumber}&clearCart=true`);
          }, 1500);
        } else {
          setStatus('error');
          setErrorMessage(data.error || 'Payment capture failed.');
        }
      } catch (err) {
        console.error('Capture error:', err);
        setStatus('error');
        setErrorMessage('Network error. Please contact support.');
      }
    };

    capturePayment();
  }, [searchParams, router]);

  return (
    <motion.div
      initial={{ opacity: 0, scale: 0.95 }}
      animate={{ opacity: 1, scale: 1 }}
      className="bg-white rounded-3xl shadow-2xl p-12 max-w-md w-full text-center"
    >
      {status === 'processing' && (
        <>
          <div className="flex justify-center mb-6">
            <Loader2 className="h-16 w-16 text-blue-500 animate-spin" />
          </div>
          <h2 className="text-2xl font-bold text-slate-800 mb-3">
            Confirming Your Payment
          </h2>
          <p className="text-slate-600">
            Please wait while we confirm your payment with PayPal...
          </p>
        </>
      )}

      {status === 'success' && (
        <>
          <div className="flex justify-center mb-6">
            <CheckCircle className="h-16 w-16 text-emerald-500" />
          </div>
          <h2 className="text-2xl font-bold text-slate-800 mb-3">
            Payment Confirmed!
          </h2>
          <p className="text-slate-600">Redirecting you to your order...</p>
        </>
      )}

      {status === 'error' && (
        <>
          <div className="flex justify-center mb-6">
            <XCircle className="h-16 w-16 text-rose-500" />
          </div>
          <h2 className="text-2xl font-bold text-slate-800 mb-3">
            Payment Failed
          </h2>
          <p className="text-slate-600 mb-6">{errorMessage}</p>
          <div className="flex flex-col gap-3">
            <button
              onClick={() => router.push('/checkout')}
              className="px-6 py-3 bg-slate-800 text-white rounded-xl font-medium hover:bg-slate-700 transition-all"
            >
              Try Again
            </button>
            <button
              onClick={() => router.push('/contact')}
              className="px-6 py-3 border border-slate-300 text-slate-600 rounded-xl font-medium hover:bg-slate-50 transition-all"
            >
              Contact Support
            </button>
          </div>
        </>
      )}
    </motion.div>
  );
}