"use client";
import React, { useMemo, useState } from "react";
import Link from "next/link";
import { Image, Button, Collapse } from "react-bootstrap";
import { usePathname } from "next/navigation"; // For active route detection

import styles from "@/styles/Component/Dashboard/DashboardNav.module.scss";
import { logout } from "@/utils/helpers";
import { useApp } from "@/components/App";
import { current_year } from "@/utils/const";
import { useRequest } from "@/components/App/request";

function DashboardNav() {
  const pathname = usePathname();
  const { request } = useRequest();
  const { userDetail, handleSidebarToggler, sideBarToggle } = useApp();
  const currentPath = pathname; // Get current path
  const [openDropdown, setOpenDropdown] = useState<string | null>(null);

  const toggleDropdown = (menu: string) => {
    setOpenDropdown(prevMenu => (prevMenu === menu ? null : menu));
  };

  const navItems = useMemo(
    () => [
      {
        title: "Dashboard",
        path: "/member/dashboard",
        icon: "/assets/dashboardIcon.png",
        isDropdown: false
      },
      {
        title: "Area Manager",
        icon: "/assets/dashboardIcon1.png",
        isDropdown: true,
        subMenu: [
          { title: "Selected Areas", path: "/member/area-manager" },
          {
            title: "New Selection",
            path: "/member/area-manager/area-selection"
          },

          {
            title: "Area Selection Logs",
            path: "/member/area-manager/area-selection-logs"
          },
          {
            title: "Map",
            path: "/member/area-manager/area-map"
          }
        ]
      },
      {
        title: "Billing",
        path: "/member/billing",
        icon: "/assets/dashboardIcon4.png",
        isDropdown: true,
        subMenu: [
          { title: "Credit Purchase", path: "/member/billing/credit-purchase" },
          { title: "Invoice", path: "/member/billing/invoice" },
          {
            title: "Statements",
            path: "/member/billing/monthly-statement"
          },
          {
            title: "Monthly Summary",
            path: "/member/billing/monthly-statement-report"
          }
          // { title: "Finance Reports", path: "/member/reports/finance" },
          // { title: "Customer Reports", path: "/member/reports/customers" }
        ]
      },
      {
        title: "Reports",
        icon: "/assets/dashboardIcon2.png",
        isDropdown: true,
        subMenu: [
          { title: "Lead Statement", path: "/member/reports" }
          // { title: "Finance Reports", path: "/member/reports/finance" },
          // { title: "Customer Reports", path: "/member/reports/customers" }
        ]
      },
      {
        title: "Graphs",
        path: "/member/graph",
        icon: "/assets/dashboardIcon3.png",
        isDropdown: false
      },      
      {
        title: "Profile",
        icon: "/assets/dashboardIcon1.png",
        isDropdown: true,
        subMenu: [
          { title: "Member Profile", path: "/member/profile/member-profile" },
          { title: "Lead Limitation", path: "/member/profile/lead-limitation" },
          { title: "Pause Account", path: "/member/profile/pause-account" }
        ]
      }
    ],
    []
  );

  function checkActiveSubItemPath(x) {
    const subMenuList = x?.subMenu || [];

    if (!subMenuList?.length) return;
    const checkVal = subMenuList.some(i => i?.path === currentPath);
    return checkVal;
  }

  async function logoutHandle() {
    try {
      // Backend logout
      await request("MEMBER_LOGOUT");
      logout();
    } catch (error) {
      console.error("Logout API failed:", error);
      // You may want to continue logout flow even if backend fails
    }
  }

  return (
    <div className={styles.DashboardNav}>
      {sideBarToggle ? (
        <Image
          src="/assets/icons/right-arrow.svg"
          alt="burger"
          className={"sideBarHamburger"}
          onClick={() => {
            handleSidebarToggler(false);
          }}
        />
      ) : (
        <Image
          src="/assets/icons/left-arrow.svg"
          alt="burger"
          className={"sideBarHamburger"}
          onClick={() => {
            handleSidebarToggler(true);
            toggleDropdown("other-string");
          }}
        />
      )}
      {/* <Image src="/assets/icons/hamburger.svg" alt="burger" className={"sideBarHamburger"} onClick={()=>handleSidebarToggler()} /> */}
      <div className={`${styles.DashboardNavHead} dash-head`}>
        <Link href="/member/dashboard" className={styles.DashboardLogo}>
          <Image src="/assets/logo.svg" alt="Company Logo" />
        </Link>
        <span>
          {userDetail?.business_name}{" "}
          <small>Account: {userDetail?.account_number}</small>
        </span>

        <ul className={styles.DashboardNavList}>
          {navItems.map((item, index) =>
            item.isDropdown ? (
              // Render Dropdown
              <li key={index} className={styles.hasDropdown}>
                <Button
                  className={`${styles.navItem} ${!sideBarToggle && (openDropdown === item.title || checkActiveSubItemPath(item)) ? styles.active : ""}`}
                  onClick={() => {
                    handleSidebarToggler(false);
                    return toggleDropdown(item.title);
                  }}
                  variant="link"
                >
                  <i>
                    <Image src={item.icon} alt={`${item.title} Icon`} />
                  </i>
                  {item.title}
                </Button>
                <Collapse
                  in={
                    !sideBarToggle &&
                    (openDropdown === item.title ||
                      checkActiveSubItemPath(item))
                  }
                >
                  <ul className={styles.dropdownMenu}>
                    {item.subMenu.map((subItem, subIndex) => (
                      <li key={subIndex}>
                        <Link
                          href={subItem.path}
                          className={`${styles.navItem} ${currentPath === subItem.path ? styles.active : ""}`}
                          onClick={e => {
                            return (
                              currentPath === subItem.path && e.preventDefault()
                            );
                          }}
                        >
                          {subItem.title}
                        </Link>
                      </li>
                    ))}
                  </ul>
                </Collapse>
              </li>
            ) : (
              // Render Single Link
              <li key={index}>
                <Link
                  href={item.path}
                  className={`${styles.navItem} ${currentPath === item.path ? styles.active : ""} `}
                  onClick={e => {
                    handleSidebarToggler(false);
                    return currentPath === item.path && e.preventDefault();
                  }} // Disable if already selected
                >
                  <i>
                    <Image src={item.icon} alt={`${item.title} Icon`} />
                  </i>
                  {item.title}
                </Link>
              </li>
            )
          )}

          <li>
            <Link
              href="/member/logout"
              onClick={e => {
                e.preventDefault();
                logoutHandle();
              }}
              className={styles.navItem}
            >
              <i>
                <Image src="/assets/dashboardIcon5.png" alt="Logout Icon" />
              </i>
              Logout
            </Link>
          </li>
        </ul>
      </div>

      <span className={`${styles.DashboardFooter} dashboard-footer-bottom`}>
        © {current_year} carbaba.co.uk. All rights reserved.
      </span>
    </div>
  );
}

export default React.memo(DashboardNav);
