"use client";

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import Logo from "@/assets/images/logo.png";
import Image from "next/image";


interface MenuItem {
  name: string;
  icon: string;
  path?: string;
  children?: MenuItem[];
}

interface SidebarProps {
  collapsed: boolean;
  setCollapsed: (val: boolean) => void;
  role: "admin" | "student";
}

export default function Sidebar({ collapsed, setCollapsed, role }: SidebarProps) {
  const pathname = usePathname();
  const router = useRouter();
  const [isMobile, setIsMobile] = useState(false);

  const [openMenus, setOpenMenus] = useState<Record<string, boolean>>({
    cms: true,
  });

  const adminMenus: MenuItem[] = [
    {
      name: "Dashboard",
      path: "/admin/dashboard",
      icon: "bi-grid-1x2-fill",
    },
    {
      name: "Students Management",
      path: "/admin/students",
      icon: "bi-people-fill",
    },
    // {
    //   name: "Manage Time Slots",
    //   path: "/admin/timeslots",
    //   icon: "bi-people-fill",
    // },
    {
      name: "Manage Time Slots",
        icon: "bi-calendar-check-fill",
      children: [
        { name: "Manage Master Slot", path: "/admin/timeslots", icon: "" },
        { name: "Edit Master Slot", path: "/admin/timeslots/edit-date", icon: "" },
        { name: "Student Slot Assignment", path: "/admin/schedule/create", icon: "" },
        { name: "Schedule Change Request", path: "/admin/schedule-requests", icon: "" },
      ],
    },
    {
      name: "Events",
      path: "/admin/events",
      icon: "bi-calendar-event-fill",
    },
    // {
    //   name: "Gallery ",
    //   path: "/admin/gallery",
    //   icon: "bi-images",
    // },
    {
      name: "Banners",
      icon: "bi-collection-fill",
      children: [
        { name: "Home Banner", path: "/admin/banner", icon: "" },
        { name: "About Banner", path: "/admin/banner/about", icon: "" },
      ],
    },
    {
      name: "CMS Management",
      icon: "bi-layout-text-window",
      children: [
        // { name: "Home", path: "/admin/cms", icon: "" },
        { name: "About Us", path: "/admin/cms/about-us", icon: "" },
        { name: "Why RKDA", path: "/admin/cms/why-rkda", icon: "" },
        { name: "Student Success", path: "/admin/cms/student-success", icon: "" },
        { name: "Student Performance", path: "/admin/cms/performances", icon: "" },
        { name: "Moments Badges", path: "/admin/cms/moment-badges", icon: "" },
        { name: "Moments Gallery", path: "/admin/cms/moments", icon: "" },
        { name: "Expert Online Classes", path: "/admin/cms/online-classes", icon: "" },
        { name: "Trust Indicators", path: "/admin/cms/trust-indicators", icon: "" },
        { name: "Training Approach", path: "/admin/cms/training-approach", icon: "" },
        { name: "Manage Marquee", path: "/admin/cms/marquee", icon: "" },
        { name: "Vision & Mission", path: "/admin/cms/vision-mission", icon: "" },
        { name: "Meet Our Guru", path: "/admin/cms/meet-guru", icon: "" },
        { name: "Footer Badge", path: "/admin/cms/footer-badge", icon: "" },
        // { name: "FAQs", path: "/admin/cms/faqs", icon: "" },
        // { name: "Privacy Policy", path: "/admin/cms/privacy-policy", icon: "" },
        // { name: "Terms & Conditions", path: "/admin/cms/terms-conditions", icon: "" },
      ],
    },
    // {
    //   name: "Vision & Mission",
    //   path: "/admin/cms/vision-mission",
    //   icon: "bi-eye-fill"
    // },
    // {
    //   name: "Meet Our Guru",
    //   path: "/admin/cms/meet-guru",
    //   icon: "bi-person-badge-fill"
    // },
    {
      name: "Contact Enquiries",
      path: "/admin/contact-enquiries",
      icon: "bi-chat-dots-fill"
    },

    {
      name: "Manage FAQs",
      path: "/admin/cms/faqs",
      icon: "bi-patch-question-fill"
    },
    {
      name: "Site Settings",
      path: "/admin/site-settings",
      icon: "bi-gear-fill",
    },
  ];

  const studentMenus: MenuItem[] = [
    {
      name: "Dashboard",
      path: "/student/dashboard",
      icon: "bi-grid-1x2-fill",
    },
    {
      name: "My Profile",
      path: "/student/profile",
      icon: "bi-person-fill",
    },
    {
      name: "My Schedule",
      path: "/student/schedule",
      icon: "bi-calendar-check-fill",
    },
  ];

  const menuItems =
    role === "admin"
      ? adminMenus
      : studentMenus;

  useEffect(() => {
    const checkScreen = () => {
      setIsMobile(window.innerWidth < 991);
    };

    checkScreen();
    window.addEventListener("resize", checkScreen);

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

  const toggleMenu = (key: string) => {
    setOpenMenus((prev) => ({
      ...prev,
      [key]: !prev[key],
    }));
  };

  const isParentActive = (children?: MenuItem[]) => {
    if (!children) return false;
    return children.some((child) => child.path === pathname);
  };

  const handleLogout = async () => {
    try {
      const logoutUrl =
        role === "admin"
          ? "/api/admin/logout"
          : "/api/student/logout";

      const loginUrl =
        role === "admin"
          ? "/admin/login"
          : "/student/login";

      await fetch(logoutUrl, {
        method: "POST",
      });

      router.push(loginUrl);
    } catch (error) {
      console.log(error);
    }
  };

  return (
    // <aside
    //   className={collapsed ? "admin-sidebar text-white shadow-lg d-flex flex-column open-sidebar" : "admin-sidebar text-white shadow-lg d-flex flex-column"}
    // >
    <aside
      className={`admin-sidebar text-white shadow-lg d-flex flex-column
          ${collapsed ? "open-sidebar" : ""}
          ${collapsed && isMobile ? "mobile-sidebar-open" : ""}
        `}
    >
      <div className="sidebar-header">

        <div>
          <div className="admin-logo"><Image src={Logo} alt="Logo" /></div>
        </div>


        {isMobile && collapsed && (
          <button
            type="button"
            className="sidebar-close-btn"
            onClick={() => setCollapsed(false)}
          >
            <i className="bi bi-x-lg"></i>
          </button>
        )}
      </div>

      <div className="admin-sidebar-scroll flex-grow-1">
        <ul className="nav flex-column sidebar-menu">
          {menuItems.map((item, index) => {
            // const active = pathname.startsWith(item.path!);
            const active = item.path ? pathname.startsWith(item.path) : false;
            const hasChildren = item.children?.length;
            const parentActive = isParentActive(item.children);
            const menuKey = `${index}`;

            if (!hasChildren) {
              return (
                <li key={item.name}>
                  <Link
                    href={item.path!}
                    className={`admin-sidebar-link ${active ? "admin-active-menu" : ""}`}
                  >
                    <i className={`bi ${item.icon}`} />
                    <span>{item.name}</span>
                  </Link>
                </li>
              );
            }

            return (
              <li key={item.name}>
                <button
                  type="button"
                  className={`admin-sidebar-link border-0 w-100 ${parentActive ? "admin-active-menu" : ""}`}
                  onClick={() => toggleMenu(menuKey)}
                >
                  <div className="d-flex align-items-center gap-2">
                    <i className={`bi ${item.icon}`} />
                    <span>{item.name}</span>
                  </div>
                  {!collapsed && (
                    <i className={`bi ${openMenus[menuKey] ? "bi-chevron-up" : "bi-chevron-down"}`} />
                  )}
                </button>

                {!collapsed && openMenus[menuKey] && (
                  <ul className="submenu-list">
                    {item.children?.map((sub) => (
                      <li key={sub.path}>
                        <Link
                          href={sub.path!}
                          className={`admin-submenu ${pathname === sub.path ? "admin-active-menu" : ""}`}
                        >
                          {sub.name}
                        </Link>
                      </li>
                    ))}
                  </ul>
                )}
              </li>
            );
          })}
        </ul>
      </div>

      <div className="sidebar-footer">
        <button
          onClick={handleLogout}
          className="btn admin-logout-btn d-flex justify-content-center text-center w-100 align-items-center gap-2"
        >
          <i className="bi bi-box-arrow-right" />

          {!collapsed && (
            <span>
              Logout
            </span>
          )}
        </button>
      </div>
    </aside>
  );
}