"use client";

import { useEffect, useState, use } from "react";
import type { Stripe } from "@stripe/stripe-js";
import { Elements } from "@stripe/react-stripe-js";
import { fetchStripeConnectContextAction } from '@/src/lib/actions/stripeConnectAction';
import {
  loadStripeConnect,
  readStripeAccountFromSession,
  writeStripeAccountToSession,
} from '@/src/lib/stripe/loadStripeConnect';
import CheckoutForm from './CheckoutForm';
import Footer from '../../../components/layout/Footer';
import { Info } from 'lucide-react';
import { useLanguage } from '@/src/lib/context/LanguageContext';
interface PayPageClientProps {
  params: Promise<{ registrationId: string }>;
  footerData: any;
  paymentPageContent?: any;
}

export default function PayPageClient({ params, footerData, paymentPageContent }: PayPageClientProps) {
  const { registrationId } = use(params);
  const [clientSecret, setClientSecret] = useState<string | null>(null);
  const [stripePromise, setStripePromise] = useState<Stripe | null>(null);
  const [connectedAccountId, setConnectedAccountId] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [amount, setAmount] = useState<number | null>(null);
  const [submissionId, setSubmissionId] = useState<string | null>(null);

  const { currentLanguage } = useLanguage();
  const t =
    currentLanguage !== "default"
      ? paymentPageContent?.translated?.checkout || paymentPageContent?.default?.checkout
      : paymentPageContent?.default?.checkout;

  const stripePublicKey = process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY || "";

  useEffect(() => {
    let cancelled = false;

    (async () => {
      try {
        if (!stripePublicKey) {
          throw new Error("Stripe configuration error. Please try again later.");
        }

        const stored = sessionStorage.getItem(`payment_${registrationId}`);
        if (!stored) {
          throw new Error("Client secret not found. Please go back and try again.");
        }

        const intentFromSecret = stored.split("_secret_")[0];
        if (intentFromSecret) {
          sessionStorage.setItem(`payment_intent_${registrationId}`, intentFromSecret);
        }

        const storedAmount = sessionStorage.getItem(`amount_${registrationId}`);
        if (storedAmount) {
          setAmount(parseInt(storedAmount, 10));
        }

        const storedSubmissionId = sessionStorage.getItem(`submission_${registrationId}`);
        setSubmissionId(storedSubmissionId || registrationId);

        let stripeAccountId = readStripeAccountFromSession(registrationId);
        if (!stripeAccountId) {
          stripeAccountId = await fetchStripeConnectContextAction();
          writeStripeAccountToSession(registrationId, stripeAccountId);
        }

        if (!stripeAccountId) {
          throw new Error(
            "Stripe connected account is missing. Please return to registration and try again."
          );
        }

        if (cancelled) {
          return;
        }

        setClientSecret(stored);
        setConnectedAccountId(stripeAccountId);

        const stripe = await loadStripeConnect(stripePublicKey, stripeAccountId);
        if (!stripe) {
          throw new Error("Unable to initialize Stripe for this franchise.");
        }

        if (cancelled) {
          return;
        }

        setStripePromise(stripe);
        setLoading(false);
      } catch (err) {
        if (!cancelled) {
          setError(err instanceof Error ? err.message : "Failed to initialize payment");
          setLoading(false);
        }
      }
    })();

    return () => {
      cancelled = true;
    };
  }, [registrationId, stripePublicKey]);

  if (loading) {
    return (
      <div
        className="min-h-[100dvh] flex flex-col items-center justify-center pt-20 px-4"
        style={{
          backgroundImage: "url(https://yefranchisees.b-cdn.net/frontend/floor-why-ye.png)",
          backgroundSize: "cover",
          backgroundPosition: "center",
          backgroundRepeat: "no-repeat",
        }}
      >
        <div className="text-center bg-white/90 backdrop-blur-sm rounded-xl p-8 shadow-lg max-w-md w-full">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[#0097DC] mx-auto mb-4" />
          <p className="text-gray-600 font-[Signika] font-medium">
            {t?.loadingCheckoutTitleText || "Loading secure checkout..."}
          </p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div
        className="min-h-[100dvh] flex flex-col items-center justify-center px-4 pt-20"
        style={{
          backgroundImage: "url(https://yefranchisees.b-cdn.net/frontend/floor-why-ye.png)",
          backgroundSize: "cover",
          backgroundPosition: "center",
          backgroundRepeat: "no-repeat",
        }}
      >
        <div className="bg-white/95 backdrop-blur-sm rounded-xl p-8 max-w-md w-full shadow-lg border-t-4 border-red-500">
          <h2 className="text-2xl font-bold text-gray-800 mb-2 font-[Signika]">Payment Error</h2>
          <p className="text-gray-600 mb-6 font-[Signika]">{error}</p>
          <a
            href="/"
            className="block w-full bg-[#0097DC] text-white py-3 rounded-lg text-center font-[Signika] font-bold hover:bg-[#0077B6] transition-colors"
          >
            Go Back Home
          </a>
        </div>
      </div>
    );
  }

  if (!clientSecret || !connectedAccountId || !stripePromise) {
    return (
      <div className="min-h-[100dvh] flex items-center justify-center pt-20">
        <p className="text-gray-600 font-[Signika]">Payment configuration error</p>
      </div>
    );
  }

  return (
    <div
      className="min-h-[100dvh] flex flex-col relative bg-gray-50/50"
      style={{
        backgroundImage: "url(https://yefranchisees.b-cdn.net/frontend/floor-why-ye.png)",
        backgroundSize: "cover",
        backgroundPosition: "center",
        backgroundRepeat: "no-repeat",
        backgroundAttachment: "fixed",
      }}
    >
      <div className="flex-1 py-12 px-4 pt-24 md:pt-32 relative z-10 flex items-center justify-center">
        <div className="w-full max-w-xl mx-auto">
          <div className="bg-white/95 backdrop-blur-xl rounded-2xl shadow-[0_8px_30px_rgb(0,0,0,0.08)] border border-gray-100 p-8 md:p-10">
            <div className="text-center mb-10">
              <h1 className="text-3xl font-extrabold text-[#2D3748] mb-3 tracking-tight font-[Signika]">
                {t?.heading || "Complete Your Payment"}
              </h1>
              <div className="bg-[#E5F4FB] border border-[#0097DC]/20 rounded-xl p-5 mt-6 flex items-start gap-4 text-left">
                <div className="w-10 h-10 rounded-xl bg-white flex items-center justify-center shadow-sm shrink-0">
                  <Info className="text-[#0097DC]" size={20} />
                </div>
                <div>
                  <h3 className="text-[14px] text-[#0097DC] font-bold uppercase tracking-widest">
                    {t?.enrollmentConfirmationHeading || "Enrollment Confirmation"}
                  </h3>
                  <p className="text-[14px] text-[#58585A] font-medium mt-1 leading-relaxed">
                    {t?.enrollmentConfirmationText ||
                      "This is your first payment for your class. This transaction secures your spot and completes the initial registration process."}
                  </p>
                </div>
              </div>
            </div>

            <Elements key={connectedAccountId} stripe={stripePromise} options={{ clientSecret }}>
              <CheckoutForm
                amount={amount}
                submissionId={submissionId || registrationId}
                clientSecret={clientSecret}
                checkoutContent={t}
              />
            </Elements>
          </div>
        </div>
      </div>

      {footerData && (
        <div className="mt-auto">
          <Footer footerData={footerData} />
        </div>
      )}
    </div>
  );
}
