import { useEffect, useState } from "react";
import PackageCard from "./PackageCard";
import usePackagesFetch from "../../../hooks/features/packages/usePackagesFetch";
import { useModal } from "../../../lib/modal-system/ModalContext";
import Image from "next/image";
import SomethingWentWrong from "../../SomethingWentWrong";
import CustomTooltip from "../../ui/CustomTooltip";

export function BuyPackageSection() {
  const [showAll, setShowAll] = useState(false);
  const { packages, loading, error, isError } = usePackagesFetch();
  const visiblePackages = showAll ? packages : packages?.slice(0, 4);
  const { openModal } = useModal();

  useEffect(() => {
    const urlParams = new URLSearchParams(window.location.search);
    const sessionId = urlParams.get("session_id");
    const modal = urlParams.get("modal");

    if (sessionId && modal === "PAYMENT_SUCCESS") {
      const packageName = localStorage.getItem(sessionId) ?? "";
      openModal("PAYMENT_SUCCESS", { packageName });
    } else {
      // some error occured
      if (modal === "PAYMENT_CANCEL") {
        openModal("PAYMENT_CANCEL", {});
      }
    }
  }, []);

  if (loading) {
    return (
      <div className="rounded-2xl p-4 glass-card-v2 sm:p-5 xl:p-7.5">
        <div className="relative z-10">
          <div className="mb-6 flex items-center justify-between gap-4">
            <div className="h-8 w-40 animate-pulse rounded-md bg-gray-200" />

            <div className="h-6 w-20 animate-pulse rounded-md bg-gray-200" />
          </div>

          <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
            {Array.from({ length: 4 }).map((_, index) => (
              <div
                key={index}
                className="rounded-xl border border-gray-100 p-5"
              >
                <div className="mb-4 h-6 w-24 animate-pulse rounded bg-gray-200" />

                <div className="mb-3 h-10 w-20 animate-pulse rounded bg-gray-200" />

                <div className="mb-6 h-4 w-16 animate-pulse rounded bg-gray-200" />

                <div className="h-10 w-full animate-pulse rounded-lg bg-gray-200" />
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  if (isError) {
    return (
      <SomethingWentWrong
        variant="section"
        title="Unable to load packages"
        description="Packages are temporarily unavailable. Please try again in a moment."
        onRetry={() => window.location.reload()}
        buttonText=""
      />
    );
  }

  if (!packages?.length) {
    return (
      <div className="glass-card-v2 rounded-2xl p-10 text-center md:p-16">
        <div className="relative z-10 mx-auto max-w-152.5">
          <Image
            src={"/images/no-packages.png"}
            alt="Empty"
            width={150}
            height={120}
            className="mx-auto mb-6"
          />

          <h3 className="font-body text-xl font-bold text-heading">
            No Packages Available Yet
          </h3>

          <p className="mt-3 font-body text-sm md:text-base text-text xl:text-lg">
            There are no packages added by admin at the moment. Please check
            back later.
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="rounded-2xl p-4 glass-card-v2 sm:p-5 xl:p-7.5">
      <div className="relative z-10">
        <div className="mb-4 xl:mb-6 flex items-center justify-between 2xl:mb-8">
          <div className="flex items-center gap-2">
            <h2 className="text-lg font-bold">Buy Package</h2>
            <CustomTooltip forWhat="packages" />
          </div>

          {packages.length > 4 && (
            <button
              type="button"
              onClick={() => setShowAll((prev) => !prev)}
              className="cursor-pointer font-body text-base font-medium text-link-1 underline"
            >
              {showAll ? "Show Less" : "View All"}
            </button>
          )}
        </div>

        <div className="grid gap-2 xl:gap-4 sm:grid-cols-2 xl:grid-cols-4">
          {visiblePackages.map((item) => (
            <PackageCard key={item.uuid} item={item} />
          ))}
        </div>
      </div>
    </div>
  );
}
