"use client";

import Image from "next/image";
import { useCallback, useEffect, useMemo, useState } from "react";
import { withCDN } from "@/src/lib/utils";
import Footer from "../../../components/layout/Footer";
import type { RegistrationInvoiceResponse } from "@/src/lib/services/registrationInvoiceService";
import type { RegisterDetailsResponse } from "@/src/lib/services/registerDetailsService";
import { generateReceiptPDF, generateStandardInvoicePDF } from "../../../lib/utils/generateInvoicePDF";
import type { InvoiceDataPayload } from "../../../lib/utils/generateInvoicePDF";
import {
  formatMoney,
  resolveRegistrationPricing,
} from "@/src/lib/utils/registrationPricing";
import { useLanguage } from "@/src/lib/context/LanguageContext";
import { FileText } from "lucide-react";
import type { ThankYouPageContentInfo, ThankYouPageDataWithTranslations } from "@/src/lib/services/thankYouPageService";
import { getPaymentStatusAction } from "@/src/lib/actions/paymentStatusAction";
import { resolvePaymentIntentIdForRegistration } from "@/src/lib/stripe/resolvePaymentIntentId";
import PaymentVerifyingState from "@/src/components/payment/PaymentVerifyingState";
import { convertTo24Hour } from "@/src/lib/utils/formatTime";
import BackButton from "@/src/components/layout/BackButton";

interface ThankYouClientProps {
  invoiceData: RegistrationInvoiceResponse | null;
  registerDetails?: RegisterDetailsResponse | null;
  paylater?: boolean;
  footerData: any;
  thankYouPageData?: ThankYouPageDataWithTranslations | null;
  registrationId: string;
  redirectStatus?: string;
  paymentIntent?: string;
  paymentIntentClientSecret?: string;
  setupIntent?: string;
  setupIntentClientSecret?: string;
}

type PagePhase = "verifying" | "confirmed" | "failed";

export default function ThankYouClient({
  invoiceData,
  registerDetails,
  paylater = false,
  footerData,
  thankYouPageData,
  registrationId,
  redirectStatus,
  paymentIntent,
  paymentIntentClientSecret,
  setupIntent,
  setupIntentClientSecret,
}: ThankYouClientProps) {
  const { currentLanguage } = useLanguage();

  const [resolvedIntentId, setResolvedIntentId] = useState<string | null>(
    paymentIntent ?? setupIntent ?? null
  );

  const [phase, setPhase] = useState<PagePhase>(paylater ? "confirmed" : "verifying");
  const [liveInvoiceStatus, setLiveInvoiceStatus] = useState<string | null>(null);
  const [livePaymentStatus, setLivePaymentStatus] = useState<string | null>(null);
  /** Keeps verifying UI visible briefly so users see confirmation in progress */
  const [verifyingGateOpen, setVerifyingGateOpen] = useState(paylater);

  const t: ThankYouPageContentInfo = useMemo(() => {
    const translated = thankYouPageData?.translated?.thankYouPage;
    const def = thankYouPageData?.default?.thankYouPage;
    return currentLanguage !== "default" && translated ? translated : def || {};
  }, [currentLanguage, thankYouPageData]);

  const invoiceRecord = Array.isArray(invoiceData?.data) ? invoiceData.data[0] : invoiceData?.data;
  const registerRecord = registerDetails?.data?.[0];

  const initialInvoiceStatus = (invoiceRecord as { status?: string })?.status ?? null;

  useEffect(() => {
    const resolved = resolvePaymentIntentIdForRegistration(registrationId, {
      paymentIntent,
      setupIntent,
      paymentIntentClientSecret,
      setupIntentClientSecret,
    });
    if (resolved) {
      setResolvedIntentId(resolved);
    }
  }, [
    registrationId,
    paymentIntent,
    setupIntent,
    paymentIntentClientSecret,
    setupIntentClientSecret,
  ]);

  const checkPaymentStatus = useCallback(async () => {
    if (paylater) {
      setPhase("confirmed");
      return;
    }

    const intentId =
      resolvedIntentId ??
      resolvePaymentIntentIdForRegistration(registrationId, {
        paymentIntent,
        setupIntent,
        paymentIntentClientSecret,
        setupIntentClientSecret,
      });

    const result = await getPaymentStatusAction(registrationId, {
      paymentIntent: intentId?.startsWith("pi_") ? intentId : null,
      setupIntent: intentId?.startsWith("seti_") ? intentId : null,
    });

    if (!result?.status || !result?.data) {
      return;
    }

    setLivePaymentStatus(result.data.payment_status ?? null);
    setLiveInvoiceStatus(result.data.invoice_status ?? null);

    if (result.data.is_paid) {
      setPhase("confirmed");
      return;
    }

    if (
      result.data.payment_status === "failed" ||
      redirectStatus === "failed"
    ) {
      setPhase("failed");
    }
  }, [
    paylater,
    registrationId,
    paymentIntent,
    setupIntent,
    paymentIntentClientSecret,
    setupIntentClientSecret,
    resolvedIntentId,
    redirectStatus,
  ]);

  useEffect(() => {
    if (paylater) {
      return;
    }

    if (redirectStatus === "failed") {
      setPhase("failed");
      return;
    }

    if (initialInvoiceStatus === "paid") {
      setPhase("confirmed");
      return;
    }

    void checkPaymentStatus();
  }, [paylater, redirectStatus, initialInvoiceStatus, checkPaymentStatus]);

  useEffect(() => {
    if (paylater) {
      setVerifyingGateOpen(true);
      return;
    }
    const timer = setTimeout(() => setVerifyingGateOpen(true), 1800);
    return () => clearTimeout(timer);
  }, [paylater]);

  useEffect(() => {
    if (paylater || phase !== "verifying") {
      return;
    }

    const interval = setInterval(() => {
      void checkPaymentStatus();
    }, 4000);

    return () => clearInterval(interval);
  }, [phase, paylater, checkPaymentStatus]);

  const paymentData = paylater ? registerRecord || {} : invoiceRecord || {};
  const submissionData = paylater
    ? registerRecord?.submission_data
    : (invoiceRecord as { class_and_customer_details?: unknown })?.class_and_customer_details ||
      (invoiceRecord as { submission_data?: unknown })?.submission_data ||
      registerRecord?.submission_data ||
      {};

  const formDataArray = Array.isArray(submissionData)
    ? submissionData
    : Object.values(submissionData as Record<string, unknown>);

  const step1 = formDataArray.find((item: unknown) => (item as { step_1?: string })?.step_1) || {};
  const step2 = formDataArray.find((item: unknown) => (item as { step_2?: string })?.step_2) || {};
  const step3 = formDataArray.find(
    (item: unknown) =>
      (item as { step_3?: string })?.step_3 === "payment_details" ||
      (item as { payment_method?: string }).payment_method
  ) || {};
  const classDetailsObj =
    formDataArray.find(
      (item: unknown) =>
        (item as { class_details?: unknown })?.class_details ||
        (typeof item === "object" && item !== null && "group_id" in (item as object))
    ) || {};
  const classDetails =
    (classDetailsObj as { class_details?: Record<string, unknown> }).class_details ||
    ((classDetailsObj as { group_id?: string }).group_id ? classDetailsObj : {});
  const zohoData =
    (submissionData as { zoho?: unknown })?.zoho ||
    formDataArray.find((item: unknown) => (item as { success?: boolean })?.success !== undefined) ||
    {};

  let transactionId = "—";
  try {
    const response = (paymentData as { response?: { id?: string; balance_transaction?: string } })?.response;
    if (response) {
      transactionId = response?.id || response?.balance_transaction || "—";
    }
    if (transactionId === "—") {
      transactionId = paymentIntent || setupIntent || "—";
    }
  } catch {
    // ignore
  }

  const programName =
    String((classDetails as { program_name?: string }).program_name || "Program").replace(/<[^>]*>/g, "") ||
    "Program";
  const instructorName = String((classDetails as { instructor_name?: string }).instructor_name || "TBD");
  const minAge = Number((classDetails as { min_age?: number }).min_age || 0);
  const maxAge = Number((classDetails as { max_age?: number }).max_age || 99);
  const childName = String((zohoData as { child?: { name?: string } })?.child?.name || (step2 as { childs_name?: string }).childs_name || "—");
  const parentName = String((zohoData as { lead?: { name?: string } })?.lead?.name || (step1 as { name?: string }).name || "—");
  const parentEmail = String((paymentData as { customer_email?: string }).customer_email || (step1 as { email?: string }).email || "—");
  const classTimeFormatted = `${(classDetails as { start_time?: string }).start_time ? convertTo24Hour((classDetails as { start_time?: string }).start_time) : "—"} - ${(classDetails as { end_time?: string }).end_time ? convertTo24Hour((classDetails as { end_time?: string }).end_time) : "—"}`;

  const discountAmount = parseFloat(String((step3 as { discount_amount?: number }).discount_amount || "0"));
  const pricing = resolveRegistrationPricing({
    classDetails: classDetails as Record<string, unknown>,
    paymentStep: step3 as Record<string, unknown>,
    invoiceTotal: parseFloat(String((paymentData as { total?: string }).total || "0")) || undefined,
    discountAmount,
  });

  const { perUnitPrice, lessonCount, totalClassValue, amountPaid, paymentFrequencyLabel, priceSuffix, couponCode } =
    pricing;

  const rawTax = parseFloat(String((paymentData as { tax?: string }).tax || "0"));
  const rawSubtotal = Math.max(0, amountPaid - rawTax);

  const paidAtRaw = (paymentData as { paid_at?: string }).paid_at;
  const paymentDateDisplay = paidAtRaw
    ? new Date(paidAtRaw).toLocaleDateString("en-US", {
        year: "numeric",
        month: "long",
        day: "numeric",
      })
    : new Date().toLocaleDateString("en-US", {
        year: "numeric",
        month: "long",
        day: "numeric",
      });

  const classDays = Array.isArray((classDetails as { day?: string[] }).day)
    ? (classDetails as { day?: string[] }).day!.join(", ")
    : String((classDetails as { day?: string }).day || "");
  const scheduleDisplay = [classDays, classTimeFormatted].filter(Boolean).join(" | ");

  const pdfPayload: InvoiceDataPayload = {
    invoiceId: String((paymentData as { id?: string }).id || "—"),
    registrationId: String((paymentData as { registration_id?: string }).registration_id || registrationId),
    transactionId: transactionId !== "—" ? transactionId : undefined,
    date: paymentDateDisplay,
    subtotal: rawSubtotal.toFixed(2),
    tax: rawTax.toFixed(2),
    taxLabel: String((classDetails as { invoice_tax_label?: string }).invoice_tax_label || ""),
    total: amountPaid.toFixed(2),
    totalClassValue: totalClassValue.toFixed(2),
    pricePerLesson: perUnitPrice.toFixed(2),
    paymentFrequencyLabel,
    priceSuffix,
    lessonCount: String(lessonCount),
    currency: String((paymentData as { currency?: string }).currency || "USD").toUpperCase(),
    paymentStatus: paylater
      ? "PAY LATER"
      : phase === "confirmed"
        ? "PAID"
        : phase === "failed"
          ? "FAILED"
          : "PENDING",
    paymentMethod: String((paymentData as { payment_method?: string }).payment_method || (paylater ? "Pay Later" : "N/A")),
    programName,
    instructorName,
    startDate: String((classDetails as { start_date?: string }).start_date || "—"),
    classTime: classTimeFormatted,
    location: String((classDetails as { location?: string }).location || "—"),
    parentName,
    parentEmail,
    parentLeadId: String((zohoData as { lead?: { cw_uid?: string } })?.lead?.cw_uid || ""),
    childName,
    childAgeGroup: `${minAge} - ${maxAge} years`,
    childId: String((zohoData as { child?: { cw_uid?: string } })?.child?.cw_uid || ""),
    companyName: (classDetails as { company_name?: string }).company_name as string | undefined,
    companyAddress: (classDetails as { company_address?: string }).company_address as string | undefined,
  };

  const isSetupIntent = transactionId.startsWith("seti_") || !!setupIntent;

  const handleDownloadReceipt = async () => await generateReceiptPDF(pdfPayload);
  const handleDownloadInvoice = async () => await generateStandardInvoicePDF(pdfPayload);

  const showFailed = !paylater && phase === "failed";
  const showVerifyingOverlay =
    !paylater && phase !== "failed" && (phase === "verifying" || !verifyingGateOpen);
  const showDetails = paylater || (phase === "confirmed" && verifyingGateOpen);

  return (
    <main className="overflow-x-hidden w-full max-w-full bg-white">
      {showVerifyingOverlay && (
        <div
          className="fixed inset-0 z-[200] flex items-center justify-center bg-[#58585A]/25 backdrop-blur-[3px] px-4"
          aria-modal="true"
          role="dialog"
          aria-labelledby="payment-verifying-title"
        >
          <PaymentVerifyingState
            variant={isSetupIntent ? "setup" : "payment"}
            title={
              isSetupIntent
                ? t.verifyingSetupText || "Verifying your account setup"
                : t.verifyingPaymentText || "Verifying your payment"
            }
            message={
              t.paymentProcessingText ||
              "Please wait while we securely confirm your transaction with our payment provider. This usually takes only a few moments."
            }
            hintText={t.paymentVerifyingHintText}
            secureBadgeText={t.paymentVerifyingSecureText}
            layout="fullscreen"
          />
        </div>
      )}

      <section
                className="relative w-full overflow-hidden py-22 md:py-20 lg:py-25   z-10
                  min-h-[340px] min-[106rem]:h-[380px]
                  px-4 md:px-8 sm:p b-0 max-[767px]:h-[300px]"
              >
                {/* Background */}
                <div className="absolute inset-0 -z-10">
                  <div
                    className="block md:hidden w-full h-full bg-cover bg-[position:50%_-26%]"
                    style={{ backgroundImage: `url('${withCDN("/About/bg_hero%20screen%20(2).png")}')` }}
                  />
                  <div
                    className="hidden md:block w-full h-full bg-cover bg-[position:50%_0%]"
                    style={{ backgroundImage: `url('${withCDN("/About/hero%20section.png")}')` }}
                  />
                </div>
      
                {/* Overlay */}
                <div className="pointer-events-none absolute inset-0" />
                <div className="max-w-[1300px] mx-auto w-full relative z-99">
                   <BackButton />
                </div>
      </section>

      <section className="relative w-full overflow-hidden pt-[100px] pb-10 md:pb-16 lg:pb-20 px-4 md:px-8 lg:px-18 xl:px-34 z-10
       mt-[-188px] z-[10] min-[106rem]:mt-[-240px] max-[767px]:mt-[-70px] md:min-h-[60vh] ">
          <div className="absolute inset-0 -z-10 max-[767px]:mt-[-50px]">
            <div
              className="block md:hidden w-full h-full bg-cover bg-top"
              style={{ backgroundImage: `url('${withCDN("/form-footer.png")}')` }}
            />
            <div
              className="hidden md:block w-full h-full bg-cover bg-top"
              style={{ backgroundImage: `url('${withCDN("/form-footer.png")}')` }}
            />
          </div>

        {showFailed ? (
          <div className="flex flex-col items-center justify-center w-full max-w-[1100px] mx-auto box-border bg-white/60 backdrop-blur-sm border-2 border-red-200 rounded-[30px] p-10 md:p-16 shadow-[6px_6px_14px_#00000010]">
            <h2 className="text-[24px] md:text-[32px] font-bold text-[#58585A] font-signika mb-3 text-center">
              {t.paymentFailedHeadingText || "Payment Failed"}
            </h2>
            <p className="text-[#828282] text-center font-signika text-[16px] md:text-[18px]">
              {t.paymentFailedText || "Your payment could not be completed. Please try again or contact support."}
            </p>
            {(livePaymentStatus || liveInvoiceStatus) && (
              <p className="text-[#828282] text-center font-signika text-[14px] mt-4">
                Status: {livePaymentStatus || liveInvoiceStatus}
              </p>
            )}
          </div>
        ) : showDetails ? (
          <div className={`relative w-full ${paylater ? "max-w-[900px]" : "max-w-[1350px]"} mx-auto bg-white rounded-[40px] mt-[-45px] shadow-[6px_6px_25px_rgba(0,0,0,0.1)] px-6 py-6 md:px-8 md:py-8  payment-wrapper ${paylater ? "lg:px-10 lg:py-8" : "lg:px-12 lg:py-10"} border-2 border-[#0097DC]/20 z-[10] box-border`}>
            <div className="flex flex-col md:flex-row gap-8 lg:gap-16 items-center lg:items-center min-w-0">
              <div className="flex-1 w-full min-w-0">
                {paylater ? (
                  <div className="flex flex-col items-center justify-center text-center py-4 md:py-6 px-4">
                    <h2 className="text-[28px] md:text-[32px] lg:text-[36px] font-bold text-[#58585A] tracking-wider mb-3">
                      CONGRATULATIONS!
                    </h2>
                    <p className="text-[18px] md:text-[18px] lg:text-[20px] text-[#58585A] font-light mb-2">
                      You have just registered your child for
                    </p>
                    <h3 className="text-[22px] md:text-[26px] font-bold text-[#0097DC] uppercase mb-5">
                      {programName}
                    </h3>
                    
                    <div className="w-full max-w-[400px] h-[1.5px] bg-[#EEEEEE] mb-5 mx-auto" />
                    
                    <p className="text-[18px] md:text-[22px] text-[#58585A] font-light leading-relaxed">
                      Our manager will contact<br/>you for more details.
                    </p>
                  </div>
                ) : (
                  <>
                    <header className="mb-5 max-[767px]:text-center">
                      <h2 className="text-[24px] lg:text-[28px] font-bold text-[#58585A] leading-tight tracking-tight uppercase">
                        {t.mainHeadingText || "THANK YOU! Your payment was successful"}
                      </h2>
                      <p className="text-[#828282] text-[16px] lg:text-[18px] mt-2 font-light">
                        {t.mainSubheadingText || "Our manager will contact you for more details."}
                      </p>
                    </header>

                    <div className="w-full h-[1.5px] bg-[#EEEEEE] mb-6" />

                <p className="text-[12px] font-bold uppercase tracking-wider text-[#0097DC] mb-2">
                  {t.recipientSectionLabel || "Recipient"}
                </p>
                <div className="space-y-0 mb-5">
                  <DetailRow label={t.parentNameLabel || "Parent"} value={parentName} />
                  <DetailRow label={t.parentEmailLabel || "Email"} value={parentEmail} />
                  <DetailRow label={t.childNameLabel || "Child"} value={childName} />
                </div>

                <p className="text-[12px] font-bold uppercase tracking-wider text-[#0097DC] mb-2">
                  {t.programSectionLabel || "Program"}
                </p>
                <div className="space-y-0 mb-5">
                  <DetailRow label={t.orderNumberLabel || "Registration ID"} value={registrationId} />
                  <DetailRow label={t.programNameLabel || "Program"} value={programName} />
                  <DetailRow label={t.studyPeriodLabel || "Start date"} value={pdfPayload.startDate} />
                  <DetailRow
                    label={t.numberOfLessonsLabel || "Number of lessons"}
                    value={String(lessonCount)}
                  />
                  {scheduleDisplay && (
                    <DetailRow label={t.classScheduleLabel || "Schedule"} value={scheduleDisplay} />
                  )}
                </div>

                <p className="text-[12px] font-bold uppercase tracking-wider text-[#0097DC] mb-2">
                  {t.paymentSectionLabel || "Payment"}
                </p>
                <div className="space-y-0 mb-6">
                  <DetailRow label={t.totalValueLabel || "Total value of the class"} value={`$${formatMoney(totalClassValue)}`} />
                  <DetailRow
                    label={t.pricePerLessonLabel || "Price"}
                    value={`$${formatMoney(perUnitPrice)} ${priceSuffix}`}
                  />
                  {paymentFrequencyLabel && (
                    <DetailRow
                      label={t.paymentFrequencyLabel || "Payment frequency"}
                      value={paymentFrequencyLabel}
                    />
                  )}
                  {couponCode && (
                    <DetailRow label={t.couponAppliedLabel || "Coupon"} value={couponCode} />
                  )}
                  <DetailRow label={t.paidLabel || "Amount paid"} value={`$${formatMoney(amountPaid)}`} isBoldValue />
                  <DetailRow label={t.paymentDateLabel || "Payment date"} value={paymentDateDisplay} />
                  <DetailRow label={t.paymentMethodLabel || "Payment method"} value={pdfPayload.paymentMethod} />
                </div>

                <div className="flex flex-wrap gap-6 mt-6">
                  <button
                    onClick={handleDownloadReceipt}
                    className="flex items-center gap-2 text-[#0097DC] font-bold hover:underline cursor-pointer"
                  >
                    <div className="bg-[#0097DC]/10 p-1.5 rounded-lg">
                      <FileText size={20} className="text-[#0097DC]" />
                    </div>
                    {t.downloadReceiptText || "Download Receipt"}
                  </button>
                  <button
                    onClick={handleDownloadInvoice}
                    className="flex items-center gap-2 text-[#0097DC] font-bold hover:underline cursor-pointer"
                  >
                    <div className="bg-[#0097DC]/10 p-1.5 rounded-lg">
                      <FileText size={20} className="text-[#0097DC]" />
                    </div>
                    {t.downloadInvoiceText || "Download Invoice"}
                  </button>
                </div>
                </>
                )}
              </div>

              <div className={`w-full flex-shrink-0 ${paylater ? "md:w-[300px] lg:w-[350px]" : "md:w-[350px] lg:w-[420px]"}`}>
                <div className={`relative w-full rounded-[40px] overflow-hidden shadow-sm border border-[#EEEEEE] max-[767px]:h-[280px] ${paylater ? "aspect-[4/3] md:aspect-square" : "aspect-square"}`}>
                  <Image
                    src={withCDN("/class-registration/photo%20(4)%20(2).png")}
                    alt="Success Child"
                    fill
                    className="object-cover"
                    priority
                  />
                </div>
              </div>
            </div>
          </div>
        ) : null}
      </section>

      <section className="relative w-full mt-[-45px] xl:mt-0 pt-[40px] lg:pt-[80px] max-[767px]:pt-0 ">
        {footerData && <Footer footerData={footerData} />}
      </section>
    </main>
  );
}

function DetailRow({
  label,
  value,
  isBoldValue = false,
}: {
  label: string;
  value: string | number;
  isBoldValue?: boolean;
}) {
  return (
    <div className="flex justify-between items-start gap-4 py-1.5 border-b border-[#EEEEEE] text-[15px] lg:text-[16px] min-w-0">
      <span className="text-[#828282] font-medium shrink-0">{label}</span>
      <span
        className={`text-right break-words min-w-0 max-w-[65%] ${
          isBoldValue ? "font-bold text-[#58585A]" : "text-[#58585A] font-semibold"
        }`}
      >
        {value}
      </span>
    </div>
  );
}
