"use client";

import { useEffect, useState } from "react";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion";
import { Separator } from "@/components/ui/separator";
import { useTranslations } from "next-intl";
import { useBooking } from "@/context/BookingContext";
import { useTotalPrice } from "@/hooks/useTotalPrice";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { SaudiRiyal } from "lucide-react";

export default function PaymentSummary() {
  const t = useTranslations("ReservationPage");
  const tCommon = useTranslations("Common");
  const { getTicketsForTotalPrice, bookingData, setPromoCode } = useBooking();
  const tickets = getTicketsForTotalPrice();
  const [isMounted, setIsMounted] = useState(false);
  const [hasCoupon, setHasCoupon] = useState(false);
  const [showPromoError, setShowPromoError] = useState(false);

  useEffect(() => {
    setIsMounted(true);
    // Initialize hasCoupon based on stored promoCode
    if (bookingData.promoCode) {
      setHasCoupon(true);
    }
  }, [bookingData.promoCode]);

  const promoCode = bookingData.promoCode || "";
  const eventId = bookingData.eventId;
  // Only use promo code if switch is enabled
  const activePromoCode = hasCoupon ? promoCode : undefined;

  const handlePromoCodeChange = (value: string) => {
    setPromoCode(value);
    setShowPromoError(false);
  };

  const handlePromoCodeBlur = () => {
    if (promoCode.trim()) {
      setShowPromoError(true);
    }
  };

  const handleSwitchChange = (checked: boolean) => {
    setHasCoupon(checked);
    if (!checked) {
      setPromoCode("");
      setShowPromoError(false);
    }
  };

  const {
    data: totalPriceData,
    isLoading,
    isError,
  } = useTotalPrice(tickets, eventId, activePromoCode);

  const isPromoInvalid =
    showPromoError &&
    promoCode.trim() &&
    hasCoupon &&
    !isLoading &&
    parseFloat(totalPriceData?.data?.discount || "0") <= 0;

  return (
    <div className="rounded-[24px] shadow-[var(--ticket-card-shadow)] overflow-hidden">
      <div className="bg-primary-anti_flash_white-main p-10 flex flex-col md:flex-row md:items-center gap-3">
        <div className="flex items-center gap-2 flex-shrink-0">
          <Switch
            id="has-coupon"
            checked={hasCoupon}
            onCheckedChange={handleSwitchChange}
          />
          <Label htmlFor="has-coupon">{t("promoCodeSwitchLabel")}</Label>
        </div>
        <div className="md:flex-1 w-full relative">
          <Input
            type="text"
            placeholder={t("promoCodePlaceholder")}
            value={promoCode}
            onChange={(e) => handlePromoCodeChange(e.target.value)}
            onBlur={handlePromoCodeBlur}
            disabled={!hasCoupon}
            className={
              isPromoInvalid ? "border-red-500 focus-visible:ring-red-500" : ""
            }
          />
          {isPromoInvalid && (
            <p className="text-[14px] text-red-500 absolute -bottom-6">
              {t("invalidPromoCode")}
            </p>
          )}
        </div>
      </div>
      <Accordion type="single" collapsible defaultValue="item-1">
        <AccordionItem value="item-1" className="rounded-[0] shadow-[none]">
          <AccordionTrigger className="text-[16px] font-bold">
            {t("paymentSummary")}
          </AccordionTrigger>
          <AccordionContent className="pt-5 flex flex-col gap-5">
            {!isMounted ? (
              <p className="text-[14px] text-gray-dark">
                {tCommon("noTicketsSelected")}
              </p>
            ) : isLoading ? (
              <p className="text-[14px] text-gray-dark">{tCommon("loading")}</p>
            ) : isError ? (
              <p className="text-[14px] text-red-500">
                {tCommon("errorLoadingSummary")}
              </p>
            ) : totalPriceData?.data && totalPriceData.data.items.length > 0 ? (
              <>
                {totalPriceData.data.items.map((item, index) => (
                  <div
                    key={index}
                    className="flex justify-between gap-20 sm:w-fit"
                  >
                    <h2 className="capitalize text-[14px] text-gray-dark w-[160px]">
                      {item.ticket_type_title}
                    </h2>
                    <p className="text-[14px] font-medium flex items-center gap-1">
                      {item.quantity} × {item.price}
                      <SaudiRiyal className="w-3.5 h-3.5" />
                    </p>
                  </div>
                ))}

                {totalPriceData.data.items.length > 0 && <Separator />}
                {parseFloat(totalPriceData.data.sub_total || "0") > 0 && (
                  <div className="flex justify-between gap-20 sm:w-fit">
                    <h2 className="capitalize text-[14px] text-gray-dark w-[160px]">
                      {t("subtotal")}
                    </h2>
                    <p className="text-[14px] font-medium flex items-center gap-1">
                      {totalPriceData.data.sub_total}{" "}
                      <SaudiRiyal className="w-3.5 h-3.5" />{" "}
                    </p>
                  </div>
                )}
                {parseFloat(totalPriceData.data.discount || "0") > 0 && (
                  <div className="flex justify-between gap-20 sm:w-fit">
                    <h2 className="capitalize text-[14px] text-green-600 w-[160px]">
                      {t("discount")}
                    </h2>
                    <p className="text-[14px] font-medium text-green-600 flex items-center gap-1">
                      <span dir="auto">-{totalPriceData.data.discount}</span>
                    </p>
                  </div>
                )}
                {parseFloat(totalPriceData.data.discount || "0") > 0 && (
                  <div className="flex justify-between gap-20 sm:w-fit">
                    <h2 className="capitalize text-[14px] text-gray-dark w-[160px]">
                      {t("subtotalAfterDiscount")}
                    </h2>
                    <p className="text-[14px] font-medium flex items-center gap-1">
                      {totalPriceData.data.sub_total_after_discount || "0"}{" "}
                      <SaudiRiyal className="w-3.5 h-3.5" />{" "}
                    </p>
                  </div>
                )}
                {parseFloat(totalPriceData.data.tax || "0") > 0 && (
                  <div className="flex justify-between gap-20 sm:w-fit">
                    <h2 className="capitalize text-[14px] text-gray-dark w-[160px]">
                      {t("tax")}
                    </h2>
                    <p className="text-[14px] font-medium flex items-center gap-1">
                      {totalPriceData.data.tax}{" "}
                      <SaudiRiyal className="w-3.5 h-3.5" />{" "}
                    </p>
                  </div>
                )}
                <Separator />

                {parseFloat(totalPriceData.data.total || "0") > 0 && (
                  <div className="flex justify-between gap-20 sm:w-fit">
                    <h2 className="capitalize text-[14px] text-gray-dark w-[160px]">
                      {t("totalAmount")}
                    </h2>
                    <p className="text-[14px] font-medium flex items-center gap-1">
                      {totalPriceData.data.total}
                      <SaudiRiyal className="w-3.5 h-3.5" />{" "}
                    </p>
                  </div>
                )}
              </>
            ) : (
              <p className="text-[14px] text-gray-dark">
                {tCommon("noTicketsSelected")}
              </p>
            )}
          </AccordionContent>
        </AccordionItem>
      </Accordion>
    </div>
  );
}
