//frontend/src/components/StudentSidebar/index.js
import { useState, useEffect } from "react";
import PropTypes from "prop-types";
import { Link, useLocation } from "react-router-dom";
import { isPathActive, deriveStudentSubmenu } from "../../utils/sidebarNavActive";
import { Button } from "@mui/material";
import { Collapse } from "react-collapse";
import {
  LayoutDashboard,
  GraduationCap,
  ChevronDown,
  BookMarked,
  Users,
  Sparkles,
  ClipboardList,
  BadgePercent,
  Waypoints,
  MessageSquare,
  LibraryBig,
  CreditCard,
  Trophy,
} from "lucide-react";

const NavIcon = ({ icon: Icon, collapsed, active }) => (
  <Icon
    size={collapsed ? 20 : 18}
    strokeWidth={1.75}
    className={`shrink-0 transition-colors ${
      active ? "text-amber-700" : "text-slate-500 group-hover:text-indigo-600"
    }`}
    aria-hidden
  />
);

const navShell = (collapsed) =>
  collapsed
    ? "!w-10 !h-10 !min-w-[40px] !p-0 !flex !justify-center"
    : "!w-full !justify-start !px-3";

const navMainClass = (collapsed, active) => {
  const shell = navShell(collapsed);
  const base =
    "group !normal-case flex gap-3 !text-[15px] items-center !py-2.5 !mx-1.5 !rounded-xl transition-colors duration-200 !border-l-[3px]";
  const state = active
    ? "!border-amber-500 !bg-[#fffbeb] !text-stone-900 !font-semibold shadow-sm"
    : "!border-transparent !font-medium !text-slate-700 hover:!bg-[#fffbeb]/80 hover:!text-slate-900";
  return `${shell} ${base} ${state}`;
};

const subNavClass = (active) =>
  `!normal-case !justify-start !w-full !text-[13px] !pl-8 !py-2 !mx-1.5 !rounded-lg flex gap-2.5 items-center transition-colors duration-200 !border-l-[3px] ${
    active
      ? "!border-amber-500 !bg-[#fffbeb] !text-stone-900 !font-semibold"
      : "!border-transparent !text-slate-600 !font-medium hover:!bg-[#fffbeb]/80"
  }`;

const AdminSidebar = ({ isCollapsed }) => {
  const { pathname } = useLocation();
  const [submenuIndex, setSubmenuIndex] = useState(null);

  useEffect(() => {
    const next = deriveStudentSubmenu(pathname);
    if (next != null) setSubmenuIndex(next);
  }, [pathname]);

  const toggleSubmenu = (index) => {
    if (isCollapsed) return;
    setSubmenuIndex(submenuIndex === index ? null : index);
  };

  return (
    <div
      className={`sidebar fixed top-0 left-0 h-full z-50 border-r border-slate-200/90 bg-gradient-to-b from-slate-50 via-white to-slate-50/80 backdrop-blur-sm transition-all duration-300 ${
        isCollapsed ? "w-[60px]" : "w-[18%] md:w-[250px]"
      }`}
    >
      {!isCollapsed && (
        <div className="flex justify-center border-b border-slate-200/70 py-4">
          <Link to="/student/dashboard" className="block transition-opacity hover:opacity-90">
            <img
              src="../../src/assets/educonnetlogo.png"
              alt="EduConnect"
              className="h-9 w-auto max-w-[132px] object-contain"
            />
          </Link>
        </div>
      )}

      <ul className={`space-y-0.5 pt-2 ${isCollapsed ? "pt-3" : ""}`}>
        <li>
          <Button
            component={Link}
            to="/student/dashboard"
            className={navMainClass(isCollapsed, isPathActive(pathname, "/student/dashboard"))}
          >
            <NavIcon icon={LayoutDashboard} collapsed={isCollapsed} active={isPathActive(pathname, "/student/dashboard")} />
            {!isCollapsed && <span>Dashboard</span>}
          </Button>
        </li>

        <li>
          <Button
            className={navMainClass(
              isCollapsed,
              pathname.startsWith("/student/dashboard/available-classes") ||
                pathname.startsWith("/student/dashboard/my-classes")
            )}
            onClick={() => toggleSubmenu(1)}
          >
            <NavIcon
              icon={GraduationCap}
              collapsed={isCollapsed}
              active={
                pathname.startsWith("/student/dashboard/available-classes") ||
                pathname.startsWith("/student/dashboard/my-classes")
              }
            />
            {!isCollapsed && <span>Class</span>}
            {!isCollapsed && (
              <span className="ml-auto text-slate-400">
                <ChevronDown
                  size={18}
                  strokeWidth={1.75}
                  className={`transition-transform duration-300 ${submenuIndex === 1 ? "rotate-180" : ""}`}
                />
              </span>
            )}
          </Button>

          {!isCollapsed && (
            <Collapse
              isOpened={submenuIndex === 1}
              theme={{
                collapse: "ReactCollapse--collapse transition-all duration-300 ease-in-out",
              }}
            >
              <ul className="mt-1 w-full space-y-0.5">
                <li>
                  <Button
                    component={Link}
                    to="/student/dashboard/available-classes"
                    className={subNavClass(isPathActive(pathname, "/student/dashboard/available-classes", { prefix: true }))}
                  >
                    <span
                      className={`h-1.5 w-1.5 shrink-0 rounded-full ${pathname.startsWith("/student/dashboard/available-classes") ? "bg-amber-500" : "bg-indigo-400"}`}
                    />
                    Available classes
                  </Button>
                </li>
                <li>
                  <Button
                    component={Link}
                    to="/student/dashboard/my-classes"
                    className={subNavClass(isPathActive(pathname, "/student/dashboard/my-classes", { prefix: true }))}
                  >
                    <span
                      className={`h-1.5 w-1.5 shrink-0 rounded-full ${pathname.startsWith("/student/dashboard/my-classes") ? "bg-amber-500" : "bg-indigo-400"}`}
                    />
                    My classes
                  </Button>
                </li>
              </ul>
            </Collapse>
          )}
        </li>

        <li>
          <Button
            className={navMainClass(
              isCollapsed,
              pathname.startsWith("/student/studypacks") || pathname.startsWith("/student/purchased-studypacks")
            )}
            onClick={() => toggleSubmenu(8)}
          >
            <NavIcon
              icon={BookMarked}
              collapsed={isCollapsed}
              active={
                pathname.startsWith("/student/studypacks") || pathname.startsWith("/student/purchased-studypacks")
              }
            />
            {!isCollapsed && <span>Study pack</span>}
            {!isCollapsed && (
              <span className="ml-auto text-slate-400">
                <ChevronDown
                  size={18}
                  strokeWidth={1.75}
                  className={`transition-transform duration-300 ${submenuIndex === 8 ? "rotate-180" : ""}`}
                />
              </span>
            )}
          </Button>

          {!isCollapsed && (
            <Collapse
              isOpened={submenuIndex === 8}
              theme={{
                collapse: "ReactCollapse--collapse transition-all duration-300 ease-in-out",
              }}
            >
              <ul className="mt-1 w-full space-y-0.5">
                <li>
                  <Button
                    component={Link}
                    to="/student/studypacks"
                    className={subNavClass(isPathActive(pathname, "/student/studypacks", { prefix: true }))}
                  >
                    <span
                      className={`h-1.5 w-1.5 shrink-0 rounded-full ${pathname.startsWith("/student/studypacks") ? "bg-amber-500" : "bg-indigo-400"}`}
                    />
                    All study packs
                  </Button>
                </li>
                <li>
                  <Button
                    component={Link}
                    to="/student/purchased-studypacks"
                    className={subNavClass(isPathActive(pathname, "/student/purchased-studypacks", { prefix: true }))}
                  >
                    <span
                      className={`h-1.5 w-1.5 shrink-0 rounded-full ${pathname.startsWith("/student/purchased-studypacks") ? "bg-amber-500" : "bg-indigo-400"}`}
                    />
                    Purchased study packs
                  </Button>
                </li>
              </ul>
            </Collapse>
          )}
        </li>

        <li>
          <Button
            component={Link}
            to="/student/dashboard/all-teachers"
            className={navMainClass(isCollapsed, isPathActive(pathname, "/student/dashboard/all-teachers"))}
          >
            <NavIcon icon={Users} collapsed={isCollapsed} active={isPathActive(pathname, "/student/dashboard/all-teachers")} />
            {!isCollapsed && <span>All teachers</span>}
          </Button>
        </li>

        <li>
          <Button
            component={Link}
            to="/student/doubt-resolver"
            className={navMainClass(isCollapsed, isPathActive(pathname, "/student/doubt-resolver", { prefix: true }))}
          >
            <NavIcon icon={Sparkles} collapsed={isCollapsed} active={pathname.startsWith("/student/doubt-resolver")} />
            {!isCollapsed && <span>AI doubt resolver</span>}
          </Button>
        </li>

        <li>
          <Button
            component={Link}
            to="/student/quizlist"
            className={navMainClass(isCollapsed, isPathActive(pathname, "/student/quizlist", { prefix: true }))}
          >
            <NavIcon icon={ClipboardList} collapsed={isCollapsed} active={pathname.startsWith("/student/quizlist")} />
            {!isCollapsed && <span>Quizzes</span>}
          </Button>
        </li>

        <li>
          <Button
            component={Link}
            to="/student/fee-waiver"
            className={navMainClass(isCollapsed, isPathActive(pathname, "/student/fee-waiver", { prefix: true }))}
          >
            <NavIcon icon={BadgePercent} collapsed={isCollapsed} active={pathname.startsWith("/student/fee-waiver")} />
            {!isCollapsed && <span>Apply fee waiver</span>}
          </Button>
        </li>

        <li>
          <Button
            component={Link}
            to="/student/personalied-path"
            className={navMainClass(isCollapsed, isPathActive(pathname, "/student/personalied-path", { prefix: true }))}
          >
            <NavIcon icon={Waypoints} collapsed={isCollapsed} active={pathname.startsWith("/student/personalied-path")} />
            {!isCollapsed && <span>AI learning path</span>}
          </Button>
        </li>

        <li>
          <Button
            component={Link}
            to="/student/message"
            className={navMainClass(isCollapsed, isPathActive(pathname, "/student/message", { prefix: true }))}
          >
            <NavIcon icon={MessageSquare} collapsed={isCollapsed} active={pathname.startsWith("/student/message")} />
            {!isCollapsed && <span>Private message</span>}
          </Button>
        </li>

        <li>
          <Button
            component={Link}
            to="/student/library"
            className={navMainClass(isCollapsed, isPathActive(pathname, "/student/library", { prefix: true }))}
          >
            <NavIcon icon={LibraryBig} collapsed={isCollapsed} active={pathname.startsWith("/student/library")} />
            {!isCollapsed && <span>Library</span>}
          </Button>
        </li>

        <li>
          <Button
            className={navMainClass(
              isCollapsed,
              pathname.startsWith("/student/dashboard/payment-history") ||
                pathname.startsWith("/student/dashboard/refund-request") ||
                pathname.startsWith("/student/dashboard/refund-history")
            )}
            onClick={() => toggleSubmenu(2)}
          >
            <NavIcon
              icon={CreditCard}
              collapsed={isCollapsed}
              active={
                pathname.startsWith("/student/dashboard/payment-history") ||
                pathname.startsWith("/student/dashboard/refund-request") ||
                pathname.startsWith("/student/dashboard/refund-history")
              }
            />
            {!isCollapsed && <span>Payment</span>}
            {!isCollapsed && (
              <span className="ml-auto text-slate-400">
                <ChevronDown
                  size={18}
                  strokeWidth={1.75}
                  className={`transition-transform duration-300 ${submenuIndex === 2 ? "rotate-180" : ""}`}
                />
              </span>
            )}
          </Button>

          {!isCollapsed && (
            <Collapse
              isOpened={submenuIndex === 2}
              theme={{
                collapse: "ReactCollapse--collapse transition-all duration-300 ease-in-out",
              }}
            >
              <ul className="mt-1 w-full space-y-0.5">
                <li>
                  <Button
                    component={Link}
                    to="/student/dashboard/payment-history"
                    className={subNavClass(isPathActive(pathname, "/student/dashboard/payment-history"))}
                  >
                    <span
                      className={`h-1.5 w-1.5 shrink-0 rounded-full ${pathname.startsWith("/student/dashboard/payment-history") ? "bg-amber-500" : "bg-indigo-400"}`}
                    />
                    Payment history
                  </Button>
                </li>
                <li>
                  <Button
                    component={Link}
                    to="/student/dashboard/refund-request"
                    className={subNavClass(isPathActive(pathname, "/student/dashboard/refund-request", { prefix: true }))}
                  >
                    <span
                      className={`h-1.5 w-1.5 shrink-0 rounded-full ${pathname.startsWith("/student/dashboard/refund-request") ? "bg-amber-500" : "bg-indigo-400"}`}
                    />
                    Refund request
                  </Button>
                </li>
                <li>
                  <Button
                    component={Link}
                    to="/student/dashboard/refund-history"
                    className={subNavClass(isPathActive(pathname, "/student/dashboard/refund-history", { prefix: true }))}
                  >
                    <span
                      className={`h-1.5 w-1.5 shrink-0 rounded-full ${pathname.startsWith("/student/dashboard/refund-history") ? "bg-amber-500" : "bg-indigo-400"}`}
                    />
                    Refund history
                  </Button>
                </li>
              </ul>
            </Collapse>
          )}
        </li>

        <li>
          <Button
            component={Link}
            to="/student/leaderboard"
            className={navMainClass(isCollapsed, isPathActive(pathname, "/student/leaderboard", { prefix: true }))}
          >
            <NavIcon icon={Trophy} collapsed={isCollapsed} active={pathname.startsWith("/student/leaderboard")} />
            {!isCollapsed && <span>Leaderboard</span>}
          </Button>
        </li>
      </ul>
    </div>
  );
};

AdminSidebar.propTypes = {
  isCollapsed: PropTypes.bool.isRequired,
  toggleSidebar: PropTypes.func,
};

export default AdminSidebar;
