"use client";
import { useEffect, useState } from "react";
import { useBreakpoint } from "@/app/components/useBreakpoint";
import { MainMenu } from "./menuType";
import Link from "next/link";

export default function SideBarNav() {
  const { isMobile, isDesktop } = useBreakpoint();
  const [activeIndex, setActiveIndex] = useState<number>(-1);
  const [megaItems, setMenuItems] = useState<MainMenu[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  const toggleMenu = (index: number) => {
    setActiveIndex(index === activeIndex ? -1 : index);
  };

  useEffect(() => {
    const fetchMenu = async () => {
      try {
        setIsLoading(true);
        // Fetch from cached API route instead of directly calling server function
        const response = await fetch("/api/menu", {
          method: "GET",
          headers: { "Content-Type": "application/json" },
          cache: "force-cache", // Use browser cache
          next: { revalidate: 3600 }, // Revalidate every hour
        });

        if (!response.ok) {
          throw new Error(`HTTP ${response.status}`);
        }

        const result = await response.json();
        if (result.success && result.data) {
          setMenuItems(result.data);
        }
      } catch (error) {
        console.error("Error fetching menu:", error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchMenu();
  }, []);

  useEffect(() => {
    if (isDesktop && megaItems.length > 0) {
      setActiveIndex(0);
    }

    if (isMobile) {
      setActiveIndex(-1);
    }
  }, [isDesktop, isMobile, megaItems.length]);

  return (
    <div className="relative z-90 max-h-lvh w-full overflow-x-hidden overflow-y-auto pt-8 pb-24 md:h-128">
      <span className="icon-thread-mashroom absolute right-5 bottom-18 z-10 h-14 w-15 bg-amber-600/50 md:bottom-5"></span>
      <div className="wrapper relative z-24">
        {isLoading ? (
          <div className="flex items-center justify-center py-10">
            <div className="h-8 w-8 animate-spin rounded-full border-2 border-gray-300 border-t-gray-900"></div>
          </div>
        ) : (
          <ul className="flex w-full flex-col gap-4 md:w-full md:flex-row md:gap-10">
            {megaItems.map((menu, i) => {
              return (
                <li
                  key={i}
                  className="border-b border-gray-950/25 pb-4 text-left"
                >
                  <button
                    onClick={() => toggleMenu(i)}
                    className={`font-macropolo w-full border-0 py-2 text-left text-xl font-medium tracking-wider uppercase duration-300 outline-none ${
                      i === activeIndex
                        ? "md:underline md:-underline-offset-22"
                        : ""
                    }`}
                  >
                    {isMobile && (
                      <div className="flex w-full flex-row items-center justify-between align-middle">
                        {menu.title}
                        <span className="flex h-6 w-6 items-center justify-between align-middle text-3xl font-light text-gray-950/50">
                          <i
                            className={`duration-300 ${
                              i === activeIndex
                                ? "icon-[ic--round-expand-less]"
                                : "icon-[ic--round-expand-more]"
                            }`}
                          ></i>
                        </span>
                      </div>
                    )}
                    {isDesktop && <>{menu.title}</>}
                  </button>

                  {activeIndex === i && (
                    <div className="top-8 flex flex-col gap-8 md:absolute md:top-8 md:left-0 md:w-full md:py-6">
                      <div className="hairline hidden h-1.5 bg-gray-950 md:flex"></div>
                      {menu.title === "Design Houses" && <p></p>}
                      <div
                        className={` ${menu.children.length === 1 ? "grid grid-cols-1 gap-10" : "grid grid-cols-2 gap-10 md:grid-cols-4"} `}
                      >
                        {menu.children.map((group, gIdx) => {
                          const isCC = group.group === "whatCC";
                          const isCatLink = group.group === "CatAllLink";

                          return (
                            <div key={gIdx}>
                              <div className="font-bogart text-md/4 capitalize">
                                {!isCC && !isCatLink && <>{group.group}</>}
                              </div>
                              <ul
                                className={`w-full ${menu.children.length === 1 ? "grid w-full grid-cols-2 md:grid-cols-4" : ""} `}
                              >
                                {group.items.map((item, k) => {
                                  const isCTA = item.type === "cta";

                                  return (
                                    <li key={k}>
                                      {isCTA ? (
                                        // ✅ CUSTOM BUTTON STYLE
                                        <Link
                                          href={item.url}
                                          className="inline-flex py-2 text-gray-950 underline-offset-5 hover:decoration-2 hover:underline font-macropolo text-base transition-all duration-300 font-medium tracking-wider uppercase underline"
                                        >
                                          {item.title}
                                        </Link>
                                      ) : (
                                        // ✅ NORMAL LINK
                                        <Link
                                          href={item.url}
                                          className={`inline-flex py-2 text-gray-950 underline-offset-5 hover:underline ${
                                            isCC || isCatLink
                                              ? "font-macropolo text-base font-medium tracking-wider uppercase underline"
                                              : "text-xs"
                                          }`}
                                        >
                                          {item.title}
                                        </Link>
                                      )}
                                    </li>
                                  );
                                })}
                              </ul>
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  )}
                </li>
              );
            })}
          </ul>
        )}{" "}
      </div>
    </div>
  );
}
