"use client";

import { PaymentElement, useElements, useStripe } from '@stripe/react-stripe-js';
import { useState } from 'react';
import { saveCardAction } from '../../../lib/actions/saveCardAction';
import { useSearchParams } from 'next/navigation';
import { useLanguage } from '@/src/lib/context/LanguageContext';
import { getLocalizedUrl } from '@/src/lib/utils/urlHelper';
import { useStripePaymentConfirm } from '@/src/lib/stripe/useStripePaymentConfirm';

interface CheckoutFormProps {
  amount?: number | null;
  submissionId?: string;
  clientSecret?: string;
  checkoutContent?: any;
}

export default function CheckoutForm({
  amount,
  submissionId,
  clientSecret,
  checkoutContent,
}: CheckoutFormProps) {
  const stripe = useStripe();
  const elements = useElements();
  const { confirm } = useStripePaymentConfirm();
  const [loading, setLoading] = useState(false);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const [saveCard, setSaveCard] = useState(false);
  const [savingCard, setSavingCard] = useState(false);
  const { currentLanguage } = useLanguage();
  const franchiseeId = useSearchParams().get('franchiseeId');


  const getPaymentIntentId = (): string | null => {
    if (!clientSecret) return null;
    const parts = clientSecret.split('_secret_');
    return parts[0] || null;
  };

  const formatAmount = (amt: number | null | undefined): string => {
    if (amt === null || amt === undefined) return '$25.00';
    if (amt === 0) return 'FREE';
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
    }).format(amt);
  };

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

    if (!stripe || !elements) {
      setErrorMsg('Payment system not ready');
      return;
    }

    setLoading(true);
    setErrorMsg(null);

    try {
      // ✅ Save card preference to backend BEFORE Stripe payment if checkbox is selected
      if (saveCard) {
        setSavingCard(true);
        const paymentIntentId = getPaymentIntentId();

        if (!paymentIntentId) {
          setErrorMsg('Payment configuration error. Unable to save card.');
          setLoading(false);
          return;
        }

        const saveResponse = await saveCardAction({
          payment_intent_id: paymentIntentId,
          gateway: 'stripe',
          save_card: true,
        });

        if (!saveResponse.success) {
          console.warn('[CheckoutForm] Card save failed, but proceeding with payment:', saveResponse.message);
        } else {
          console.log('[CheckoutForm] ✓ Card preference saved on backend');
        }

        setSavingCard(false);
      }

      // Stripe sends the customer back to this absolute URL from its own domain,
      // so it is the only carrier of context across the hop — the tenant has to
      // be in it, not just the language.
      const returnUrl = getLocalizedUrl(
        `${window.location.origin}/thank-you/${submissionId || 'default'}`,
        currentLanguage,
        franchiseeId
      );

      const result = await confirm({
        stripe,
        elements,
        clientSecret: clientSecret!,
        returnUrl,
      });

      if (!result.ok) {
        setErrorMsg(result.error || 'Payment failed');
        return;
      }

      if (!result.redirecting) {
        const params = new URLSearchParams({ redirect_status: "succeeded" });
        const intentId = getPaymentIntentId();
        if (intentId) {
          params.set(
            intentId.startsWith("seti_") ? "setup_intent" : "payment_intent",
            intentId
          );
        }
        const separator = returnUrl.includes("?") ? "&" : "?";
        window.location.href = `${returnUrl}${separator}${params.toString()}`;
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'An unexpected error occurred';
      setErrorMsg(errorMessage);
    } finally {
      setLoading(false);
      setSavingCard(false);
    }
  };

  return (
    <form onSubmit={handlePay} className="space-y-7 mt-4">
      {/* Error Message */}
      {errorMsg && (
        <div className="bg-red-50 border-l-4 border-red-500 text-red-700 p-4 rounded-md shadow-sm">
          <p className="font-medium font-[Signika]">{errorMsg}</p>
        </div>
      )}

      {/* Stripe Payment Element - Default fields but styled by PayPageClient */}
      <div className="bg-gray-50/50 p-2 rounded-xl border border-transparent">
        <PaymentElement />
      </div>

      {/* Save Card Checkbox */}
      <div className="flex items-center gap-3 px-1">
        <div className="relative flex items-center">
          <input
            type="checkbox"
            id="saveCard"
            checked={saveCard}
            onChange={(e) => setSaveCard(e.target.checked)}
            className="w-5 h-5 border-gray-300 rounded text-[#0097DC] focus:ring-[#0097DC] cursor-pointer transition-colors"
          />
        </div>
        <label
          htmlFor="saveCard"
          className="text-sm text-gray-700 font-medium font-[Signika] cursor-pointer select-none"
        >
          {checkoutContent?.saveMyCardText || 'Save my card details for future payments'}
        </label>
      </div>

      {/* Payment Button */}
      <button
        type="submit"
        disabled={!stripe || loading || savingCard}
        className="w-full relative overflow-hidden bg-[#0097DC] hover:bg-[#0077B6] text-white font-bold py-4 px-6 rounded-xl text-lg disabled:opacity-70 disabled:cursor-not-allowed transition-all duration-300 shadow-md hover:shadow-xl flex items-center justify-center font-[Signika]"
      >
        {loading || savingCard ? (
          <span className="flex items-center gap-2">
            <svg className="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
              <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
              <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            {savingCard ? 'Saving Card...' : 'Processing Payment...'}
          </span>
        ) : (
          amount === 0 ? (checkoutContent?.setupButtonText || 'Setup your account') : `${checkoutContent?.payButtonText || 'Pay Securely'} - ${formatAmount(amount)}`
        )}
      </button>

      {/* Info Text */}
      <p className="text-xs text-gray-500 text-center flex items-center justify-center gap-2 font-[Signika]">
        <svg className="w-4 h-4 text-green-500" 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>
        Your payment is secure and encrypted.
      </p>
    </form>
  );
}
