"use client";

import { useState } from "react";
import { ChevronDown, ChevronUp } from "lucide-react";
import { ClassDetailsType } from "@/src/lib/context/ClassDetailsContext";
import type { CheckoutPageContentInfo } from "@/src/lib/services/checkoutPageService";
import { getFeeBasisPriceLabel } from "@/src/lib/utils/registrationPricing";
import { convertTo24Hour } from "@/src/lib/utils/formatTime";

interface RegistrationSidebarProps {
  classDetails: ClassDetailsType;
  paymentPlans: any[];
  finalPrice: string | number;
  originalPrice: number;
  totalProgramPrice?: number;
  pageContent?: CheckoutPageContentInfo | null;
  displayPaymentAmount?: number;
}

export default function RegistrationSidebar({
  classDetails,
  paymentPlans,
  finalPrice,
  originalPrice,
  totalProgramPrice: totalProgramPriceProp,
  pageContent,
  displayPaymentAmount,
}: RegistrationSidebarProps) {
  const [classInfoOpen, setClassInfoOpen] = useState(false);
const [paymentInfoOpen, setPaymentInfoOpen] = useState(false);

const [scheduleOpen, setScheduleOpen] = useState(false);
const [PaymentOpen, setPaymentOpen] = useState(false);

  const t = (key: keyof CheckoutPageContentInfo, fallback: string) =>
    (pageContent?.[key] as string | undefined) || fallback;

  const totalInstallments = paymentPlans?.length ?? 0;

  const formatShortDate = (raw?: string | null) => {
    if (!raw) return "";
    const d = new Date(raw);
    if (isNaN(d.getTime())) return raw;
    return d.toLocaleDateString("en-GB", { day: '2-digit', month: 'short' });
  };

  const formattedStudyPeriod = classDetails.end_date && classDetails.start_date
    ? `${formatShortDate(classDetails.start_date)} - ${formatShortDate(classDetails.end_date)}`
    : classDetails.start_date ? formatShortDate(classDetails.start_date) : "";

  const formattedDays = classDetails.day?.map((d: string) => d.slice(0, 3)).join(", ") || "";

  const formatDueDate = (raw?: string | null) =>
    raw
      ? new Date(raw).toLocaleDateString("en-GB", {
          day: "2-digit",
          month: "short",
          year: "numeric",
        })
      : null;
  const firstDueLabel = formatDueDate(paymentPlans?.[0]?.due_date);
  const nextDueLabel =
    totalInstallments > 1 ? formatDueDate(paymentPlans?.[1]?.due_date) : null;

  const hasPaymentPlans = totalInstallments > 0;
  /** Mirrors RegisterProgramForm: API may expose unit rate as `value` or `price`. */
  const unitPrice =
    typeof originalPrice === "number" && !Number.isNaN(originalPrice) ? originalPrice : parseFloat(String(originalPrice)) || 0;
  const fallbackLessonCount = parseInt(classDetails.number_of_lessons) || 1;
  const totalClassValue =
    totalProgramPriceProp ?? Math.max(0, unitPrice * fallbackLessonCount);
  const formatMoney = (value: number) =>
    Number.isInteger(value) ? value.toString() : value.toFixed(2);

  const paymentFrequency = String(
    classDetails?.payment_charges_frequency || "per_lesson",
  ).toLowerCase();
  const frequencyLabels: Record<string, string> = {
    weekly: "Weekly",
    monthly: "Monthly",
    daily: "Daily",
    per_lesson: "Per lesson",
  };
  const paymentFrequencyLabel =
    frequencyLabels[paymentFrequency] ||
    paymentFrequency.replace(/_/g, " ");
  const feeBasis = String(classDetails?.fee_basis || "per_lesson").toLowerCase();
  const feeBasisPriceLabel = getFeeBasisPriceLabel(classDetails?.fee_basis);
  const isMonthly = feeBasis === "per_month" || feeBasis === "monthly";
  const feeTypeLabel = isMonthly ? "Monthly" : "Per Lesson";

  const perUnitDisplayAmount = unitPrice;
  const breakdownCount = fallbackLessonCount;
  const breakdownUnit = breakdownCount === 1 ? "lesson" : "lessons";

  // What we render as the "Payment Amount" big number / button-style headline.
  // Always the first installment from the payment-plans API when available;
  // otherwise fall back to the final per-class price (after coupon).
  const firstPlanAmount = hasPaymentPlans
    ? parseFloat(paymentPlans[0]?.amount) || 0
    : null;
  const headlineAmount =
    displayPaymentAmount !== undefined
      ? displayPaymentAmount
      : firstPlanAmount !== null
      ? firstPlanAmount
      : typeof finalPrice === "number"
      ? finalPrice
      : parseFloat(String(finalPrice)) || 0;

  return (
    <div className="w-full md:w-[320px] bg-white rounded-[28px] p-[30px] pt-[40px] shadow-[0px_14px_24px_#00000024]">
      <h3 className="text-center text-[18px] font-bold text-[#555] mb-8">
        {t("sidebarTitleText", "ORDER DETAILS")}
      </h3>
      <h2 className="text-[40px] font-bold text-[#0097dc] leading-none uppercase">
        {classDetails.program?.name}
      </h2>
      <p className="text-[#888] mt-2 mb-5 uppercase">
        {classDetails.group_name}
      </p>

      {/* ------------- CLASS INFO ACCORDION ------------- */}
      <div className="border-b border-[#828282] pb-0 mb-6">
        <button
         onClick={() => {
           const newState = !classInfoOpen;
           setClassInfoOpen(newState);
            if (newState) {
              setPaymentInfoOpen(false);
            }
         }}
          className="w-full flex items-center justify-between pb-3 cursor-pointer"
        >
          <h4 className="text-[18px] font-bold uppercase text-[#555]">
            {t("classInfoTitleText", "Class Info")}
          </h4>
          {classInfoOpen ? (
            <ChevronUp className="w-5 h-5 text-[#666]" />
          ) : (
            <ChevronDown className="w-5 h-5 text-[#666]" />
          )}
        </button>

        {classInfoOpen && (
          <div className="space-y-6 mt-2 pb-5">
            <div className="border-l-2 border-[#D9D9D9] pl-4 mb-5">
              <p className="text-[#0097DC] text-[13px] font-regular uppercase">{t("studyPeriodLabel", "Study Period")}</p>
              <p className="text-[18px] text-[#58585A]">{formattedStudyPeriod}</p>
            </div>

            <div className="border-l-2 border-[#D9D9D9] pl-4 mb-5">
              <p className="text-[#0097dc] text-[13px] font-regular uppercase">{t("daysLabel", "Days")}</p>
              <p className="text-[18px] text-[#58585A]">{formattedDays}</p>
            </div>

            <div className="border-l-2 border-[#D9D9D9] pl-4 mb-5">
              <p className="text-[#0097dc] text-[13px] font-regular uppercase">{t("classTimeLabel", "Class Time")}</p>
              <p className="text-[18px] text-[#58585A]">{classDetails.start_time ? convertTo24Hour(classDetails.start_time) : ""} - {classDetails.end_time ? convertTo24Hour(classDetails.end_time) : ""}</p>
            </div>

            <div className="border-l-2 border-[#D9D9D9] pl-4 mb-5">
              <p className="text-[#0097dc] text-[13px] font-regular uppercase">{t("numberOfLessonsLabel", "Number Of Lessons")}</p>
              <p className="text-[18px] text-[#58585A]">
                {classDetails.number_of_lessons}{" "}
                <span className="text-[#828282] text-[16px] font-light">| {classDetails.frequency}</span>
              </p>
            </div>

            <div className="border-l-2 border-[#D9D9D9] pl-4">
              <button
                onClick={() => setScheduleOpen(!scheduleOpen)}
                className="flex items-center justify-start gap-3 w-full mb-3 cursor-pointer"
              >
                <p className="text-[#0097dc] text-[13px] font-regular uppercase">{t("classScheduleLabel", "Class Schedule")}</p>
                {scheduleOpen ? (
                  <ChevronUp className="w-4 h-4 text-[#666]" />
                ) : (
                  <ChevronDown className="w-4 h-4 text-[#666]" />
                )}
              </button>
              {scheduleOpen && (
                <div className="space-y-2 text-[15px] text-[#666]">
                  <p className="text-[18px] text-[#58585A]">
                    {formattedDays} | {classDetails.start_time ? convertTo24Hour(classDetails.start_time) : ""} - {classDetails.end_time ? convertTo24Hour(classDetails.end_time) : ""}
                  </p>
                </div>
              )}
            </div>
          </div>
        )}
      </div>

      {/* ----------- PAYMENT INFO ACCORDION ------------- */}
      <div className="pt-0 mb-6 pb-3 border-b border-[#828282]">
        <button
          onClick={() => {
            const newState = !paymentInfoOpen;
            setPaymentInfoOpen(newState);
            if (newState) {
              setClassInfoOpen(false);
            }
          }}
          className="w-full flex items-center justify-between cursor-pointer"
        >
          <h4 className="text-[18px] font-bold uppercase text-[#585858]">{t("paymentInfoTitleText", "Payment Info")}</h4>
          {paymentInfoOpen ? (
            <ChevronUp className="w-5 h-5 text-[#666]" />
          ) : (
            <ChevronDown className="w-5 h-5 text-[#666]" />
          )}
        </button>

        {paymentInfoOpen && (
          <div className="pt-5">
            <div className="border-l-2 border-[#D9D9D9] pl-4 mb-5">
              <p className="text-[#0097dc] text-[14px] font-regular uppercase">{t("totalValueLabel", "Total Value of the Class")}</p>
              <p className="text-[18px] text-[#58585A]">
                ${formatMoney(totalClassValue)}
                <span className="text-[#58585A] text-[14px]">
                  {" "}| ${formatMoney(perUnitDisplayAmount)} x {breakdownCount} {breakdownUnit}
                </span>
              </p>
            </div>

            <div className="border-l-2 border-[#D9D9D9] pl-4 mb-5">
              <p className="text-[#0097dc] text-[14px] font-regular uppercase">
                {feeBasisPriceLabel}
              </p>
              <p className="text-[18px] text-[#58585A]">$ {formatMoney(perUnitDisplayAmount)}</p>
            </div>

            <div className="border-l-2 border-[#D9D9D9] pl-4 mb-5">
              <p className="text-[#0097dc] text-[14px] font-regular uppercase">
                {t("paymentFrequencyLabel", "Payment Frequency")}
              </p>
              <p className="text-[18px] text-[#58585A]">{paymentFrequencyLabel}</p>
            </div>

            <div className="border-l-2 border-[#D9D9D9] pl-4 mb-5">
              <p className="text-[#0097dc] text-[14px] font-regular uppercase">{t("feeTypeLabel", "Fee Type")}</p>
              <p className="text-[18px] text-[#828282]">{feeTypeLabel}</p>
            </div>

            <div className="border-l-2 border-[#D9D9D9] pl-4 mb-5">
              <button
                onClick={() => setPaymentOpen(!PaymentOpen)}
                className="flex items-center justify-start gap-3 w-full mb-3 cursor-pointer"
              >
                <p className="text-[#0097dc] text-[14px] font-regular uppercase">{t("paymentScheduleLabel", "Payment Schedule")}</p>
                {PaymentOpen ? (
                  <ChevronUp className="w-4 h-4 text-[#666]" />
                ) : (
                  <ChevronDown className="w-4 h-4 text-[#666]" />
                )}
              </button>
              {PaymentOpen && (
                <div className="text-[15px] text-[#666]">
                  {paymentPlans.length > 0 ? (
                    <div className="relative">
                      <div className="max-h-[220px] overflow-y-auto space-y-3 pr-2 [scrollbar-width:thin] [scrollbar-color:#0097dc_transparent] [&::-webkit-scrollbar]:w-[3px] [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-thumb]:bg-[#0097dc] [&::-webkit-scrollbar-thumb]:rounded-full hover:[&::-webkit-scrollbar-thumb]:bg-[#007bb5]">
                        {paymentPlans.map((plan, index) => (
                          <div key={index}>
                            <p className="text-[14px] text-[#58585A] font-light">
                              {t("paymentLabel", "Payment")} {index + 1}
                            </p>
                            <div className="flex justify-start items-center gap-1 text-[#58585A]">
                              <span className="font-regular text-[20px]">
                                ${formatMoney(parseFloat(plan.amount) || 0)}
                              </span>
                              <span className="font-light text-[14px]">
                                | {new Date(plan.due_date).toLocaleDateString("en-GB", { day: '2-digit', month: 'short', year: 'numeric' })}
                              </span>
                            </div>
                          </div>
                        ))}
                      </div>
                      {paymentPlans.length > 3 && (
                        <div className="pointer-events-none absolute bottom-0 left-0 right-0 h-8 bg-gradient-to-t from-white to-transparent" />
                      )}
                    </div>
                  ) : (
                    <p className="text-[13px] italic py-2">{t("noFuturePlansText", "No future plans available")}</p>
                  )}
                </div>
              )}
            </div>
          </div>
        )}
      </div>

      {/* Payment */}
      <div className="mt-0 pt-0">
        <p className="text-[#828282] text-[16px]">
          {t("paymentAmountLabel", "Payment Amount")}
        </p>

        <div className="flex items-baseline flex-wrap gap-x-2 leading-tight">
          <h2 className="text-[30px] font-bold text-[#58585A] leading-tight">
            $ {String(classDetails?.payer_id) === "2" ? "0" : formatMoney(headlineAmount)}
          </h2>
          {String(classDetails?.payer_id) !== "2" && firstDueLabel && (
            <span className="text-[16px] font-semibold text-[#0097dc] whitespace-nowrap">
              {t("paymentForText", "for")} {firstDueLabel}
            </span>
          )}
        </div>

        {String(classDetails?.payer_id) !== "2" && (
          totalInstallments > 1 ? (
            <p className="text-[13px] text-[#58585A] mt-1 leading-snug">
              {t("paymentLabel", "Payment")} 1 {t("paymentOfText", "of")}{" "}
              {totalInstallments}
              {nextDueLabel && (
                <>
                  {" · "}
                  <span className="text-[#828282]">
                    {t("nextPaymentText", "next")} {nextDueLabel}
                  </span>
                </>
              )}
            </p>
          ) : totalInstallments === 1 ? (
            <p className="text-[13px] text-[#58585A] mt-1 leading-snug">
              {t("oneTimePaymentText", "One-time payment")}
            </p>
          ) : null
        )}
      </div>
    </div>
  );
}
