'use client';

import { useEffect, useState, Suspense } from 'react';
import { Elements } from '@stripe/react-stripe-js';
import { getStripeJs } from '../../../lib/stripe';
import PaymentForm from '../../components/PaymentForm';
import { useSearchParams } from 'next/navigation';

// Loading component for Suspense fallback
function PaymentLoading() {
  return (
    <div className="flex justify-center items-center p-8">
      <div className="text-lg">Loading payment...</div>
    </div>
  );
}

// Inner component that uses useSearchParams
function PaymentContent() {
  const [stripePromise, setStripePromise] = useState<any>(null);
  const [clientSecret, setClientSecret] = useState<string>('');
  const [loading, setLoading] = useState(true);
  const [paymentSuccess, setPaymentSuccess] = useState(false);
  const [error, setError] = useState<string>('');
  
  const searchParams = useSearchParams();
  const amount = parseFloat(searchParams.get('amount') || '0');
  const consultationType = searchParams.get('type') || 'general';
  const customerEmail = searchParams.get('email') || 'customer@example.com';
  const customerName = searchParams.get('name') || 'Customer Name';

  useEffect(() => {
    getStripeJs().then(setStripePromise);
  }, []);

  useEffect(() => {
    if (amount > 0) {
      createPaymentIntent();
    }
  }, [amount]);

  // THIS IS WHERE WE CALL THE PAYMENT INTENT API
  const createPaymentIntent = async () => {
    try {
      setLoading(true);
      setError('');

      const response = await fetch('/api/frontend/payment-intent', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          amount,
          consultationType,
          customerEmail,
          customerName,
        }),
      });

      const data = await response.json();
      
      if (!response.ok) {
        throw new Error(data.error || 'Failed to create payment intent');
      }

      setClientSecret(data.clientSecret);
    } catch (error) {
      console.error('Error creating payment intent:', error);
      setError(error instanceof Error ? error.message : 'Something went wrong');
    } finally {
      setLoading(false);
    }
  };

  const handlePaymentSuccess = (paymentIntentId: string, transactionId: string) => {
    setPaymentSuccess(true);
    // You can redirect or show success message
    console.log('Payment successful:', { paymentIntentId, transactionId });
    
    // Optionally redirect to success page
    // window.location.href = `/payment/success?transaction=${transactionId}`;
  };

  const handlePaymentError = (error: string) => {
    console.error('Payment error:', error);
    setError(error);
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center p-8">
        <div className="text-lg">Creating payment session...</div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="max-w-md mx-auto p-6 text-center">
        <div className="text-red-600 text-6xl mb-4">❌</div>
        <h1 className="text-2xl font-bold mb-2">Payment Error</h1>
        <p className="text-gray-600 mb-4">{error}</p>
        <button 
          onClick={() => window.location.reload()}
          className="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700"
        >
          Try Again
        </button>
      </div>
    );
  }

  if (paymentSuccess) {
    return (
      <div className="max-w-md mx-auto p-6 text-center">
        <div className="text-green-600 text-6xl mb-4">✓</div>
        <h1 className="text-2xl font-bold mb-2">Payment Successful!</h1>
        <p className="text-gray-600 mb-4">
          Thank you for your payment. Your consultation has been scheduled.
        </p>
        <button 
          onClick={() => window.location.href = '/'}
          className="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700"
        >
          Return Home
        </button>
      </div>
    );
  }

  return (
    <div className="max-w-md mx-auto p-6">
      <h1 className="text-2xl font-bold mb-2">Complete Your Payment</h1>
      <p className="text-gray-600 mb-6">
        {consultationType} Consultation - PKR {amount.toFixed(2)}
      </p>

      {clientSecret && stripePromise && (
        <Elements stripe={stripePromise} options={{ clientSecret }}>
          <PaymentForm
            amount={amount}
            consultationType={consultationType}
            customerEmail={customerEmail}
            customerName={customerName}
            onSuccess={handlePaymentSuccess}
            onError={handlePaymentError}
          />
        </Elements>
      )}
    </div>
  );
}

// Main component with Suspense boundary
export default function PaymentPage() {
  return (
    <Suspense fallback={<PaymentLoading />}>
      <PaymentContent />
    </Suspense>
  );
}