"use client";

import { apiCall } from "@/utils/callApi";
import React, { useEffect, useState } from "react";
import Link from "next/link";

let cachedCategories: any = null;
let cachedPromise: any = null;

let cachedSettings: any = null;
let cachedSettingsPromise: any = null;

const AppFooter = () => {
  const [categories, setCategories] = useState<any[]>([]);
  const [settings, setSettings] = useState<any>({});
  const [generalsettings, setGeneralSettings] = useState<any>(null);
  const [openSection, setOpenSection] = useState<string | null>(null);
  const [isMobile, setIsMobile] = useState(false);

  const toggleSection = (section: string) => {
    setOpenSection((prev) => (prev === section ? null : section));
  };

  useEffect(() => {
    const handleResize = () => {
      setIsMobile(window.innerWidth <= 767);
    };

    handleResize();

    window.addEventListener("resize", handleResize);

    return () => window.removeEventListener("resize", handleResize);
  }, []);

  useEffect(() => {
    const storedSettings =
      localStorage.getItem("Generalsettings") ||
      localStorage.getItem("general-settings");

    if (storedSettings) {
      try {
        setGeneralSettings(JSON.parse(storedSettings));
      } catch (error) {
        console.error("Invalid general settings JSON", error);
      }
    }
  }, []);

  const fetchCategories = async () => {
    try {
      if (cachedCategories) {
        setCategories(cachedCategories);
        return;
      }

      if (!cachedPromise) {
        cachedPromise = apiCall<any>("/clientapi/home").then((res) => {
          const ctg = res.data?.footerCategories || [];
          cachedCategories = ctg;
          return ctg;
        });
      }

      const ctg = await cachedPromise;
      setCategories(ctg);
    } catch (error) {
      console.error("Category fetch error", error);
    }
  };

  const fetchGeneralSettings = async () => {
    try {
      if (cachedSettings) {
        setSettings(cachedSettings);
        return;
      }

      if (!cachedSettingsPromise) {
        cachedSettingsPromise = apiCall<any>("/api/general-settings").then(
          (res) => {
            const stg = res.data?.data || {};
            cachedSettings = stg;
            return stg;
          },
        );
      }

      const stg = await cachedSettingsPromise;
      setSettings(stg);
    } catch (error) {
      console.error("General settings fetch error", error);
    }
  };

  useEffect(() => {
    fetchCategories();
    fetchGeneralSettings();
  }, []);

  const shouldShowCategories = !isMobile || openSection === "categories";
  const shouldShowLinks = !isMobile || openSection === "links";

  return (
    <footer className="footercontainer">
      <div className="footertp">
        <div className="container-xxl container px-3">
          <div className="-mx-2 flex flex-wrap justify-between xl:-mx-6">
            {/* Logo Column */}
            <div className="xxl:w-1/3 footercolumnone w-full px-2 sm:w-full md:w-1/3 lg:w-1/3 xl:w-1/3 xl:px-6">
              <div className="footerlogoouter">
                <div className="footerlogo">
                  <Link href="/">
                    <img
                      alt="Footer Logo"
                      src={
                        generalsettings?.footerLogo ||
                        settings?.footerLogo ||
                        "/assets/images/logo.png"
                      }
                    />
                  </Link>
                </div>

                <div className="footeraddres p-0">
                  <p>
                    A store that provides you an extensive collection of men’s
                    clothing for every occasion
                  </p>
                </div>
              </div>
            </div>
            <div className="xxl:w-7/12 w-full px-2 sm:w-full md:w-7/12 lg:w-7/12 xl:w-7/12 xl:px-6">
              <div className="-mx-2 flex flex-wrap xl:-mx-6">
                {/* Categories Column */}
                <div className="xxl:w-6/12 sm:md-0 footercolumntwo mb-2 w-full px-2 sm:w-6/12 md:w-1/6 lg:w-6/12 xl:w-6/12 xl:px-6">
                  <div
                    className={`footernav footerAccordionItem ${
                      openSection === "categories" ? "active" : ""
                    }`}
                  >
                    <button
                      type="button"
                      className="footerAccordionButton footerheading"
                      onClick={() => toggleSection("categories")}
                    >
                      <span>Categories</span>
                      <span className="footerAccordionIcon">
                        {openSection === "categories" ? "−" : "+"}
                      </span>
                    </button>

                    <ul className="footerAccordionList">
                      {categories?.length > 0 ? (
                        categories.map((cat: any) => (
                          <li key={cat._id || cat.id}>
                            <Link href={`/products?category=${cat.slug}`}>
                              {cat.name}
                            </Link>
                          </li>
                        ))
                      ) : (
                        <li>No categories found</li>
                      )}
                    </ul>
                  </div>
                </div>

                {/* Quick Links Column */}
                <div className="xxl:w-6/12 sm:md-0 footercolumntwo mb-2 w-full px-2 sm:w-6/12 md:w-1/6 lg:w-6/12 xl:w-6/12 xl:px-6">
                  <div
                    className={`footernav footernavbx footerAccordionItem ${
                      openSection === "links" ? "active" : ""
                    }`}
                  >
                    <button
                      type="button"
                      className="footerAccordionButton footerheading"
                      onClick={() => toggleSection("links")}
                    >
                      <span>Quick Links</span>
                      <span className="footerAccordionIcon">
                        {openSection === "links" ? "−" : "+"}
                      </span>
                    </button>

                    <ul className="footerAccordionList">
                      <li>
                        <Link href="/">Home</Link>
                      </li>
                      <li>
                        <Link href="/about">About Us</Link>
                      </li>
                      <li>
                        <Link href="/blog">Blog</Link>
                      </li>
                      <li>
                        <Link href="/contact-us">Contact Us</Link>
                      </li>
                      <li>
                        <Link href="/privacy-policy">Privacy &amp; Policy</Link>
                      </li>
                      <li>
                        <Link href="/terms-and-conditions">Terms &amp; Conditions</Link>
                      </li>
                      <li>
                        <Link href="/disclaimer">Disclaimer</Link>
                      </li>
                      <li>
                        <Link href="/cookie-policy">Cookie Policy</Link>
                      </li>
                    </ul>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="footerbtm">
        <div className="container-xxl container px-3">
          <p>
            Copyright © 2026 <Link href="/">Dulhe Sahab</Link>. All Rights
            Reserved
          </p>
        </div>
      </div>
    </footer>
  );
};

export default React.memo(AppFooter);
