"use client";

import React, { useState, useEffect } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Button } from "../ui/button";
import {
  LayoutDashboard,
  Users,
  Settings,
  Menu,
  X,
  LogOut,
} from "lucide-react";
import { signOut } from "next-auth/react";

const ModeratorSideBar: React.FC = () => {
  const pathname = usePathname();
  const [sidebarOpen, setSidebarOpen] = useState(false);

  // Close sidebar when navigating on mobile
  useEffect(() => {
    if (typeof window !== "undefined" && window.innerWidth < 1024) {
      setSidebarOpen(false);
    }
  }, [pathname]);

  // Handle resize events with debounce for better performance
  useEffect(() => {
    if (typeof window === "undefined") return;

    let timeoutId: NodeJS.Timeout;

    const handleResize = () => {
      // Clear previous timeout
      clearTimeout(timeoutId);

      // Set new timeout to debounce the resize event
      timeoutId = setTimeout(() => {
        if (window.innerWidth < 1024) {
          setSidebarOpen(false);
        }
      }, 100);
    };

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

  // Close sidebar on ESC key
  useEffect(() => {
    const handleEscKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        setSidebarOpen(false);
      }
    };

    document.addEventListener("keydown", handleEscKey);
    return () => document.removeEventListener("keydown", handleEscKey);
  }, []);

  // Improved isActive function that handles parent paths better
  const isActive = (path: string) => {
    // Exact match
    if (pathname === path) return true;

    // Check if it's a parent path
    if (path !== "/moderator" && pathname.startsWith(path)) return true;

    return false;
  };

  const logoutHandler = async () => {
    await signOut({
      redirectTo: "/auth/login",
      callbackUrl: "/auth/login",
    });
  };

  return (
    <>
      {/* Mobile Toggle Button - Visible on mobile only */}
      <div className="fixed right-4 top-4 z-50 md:hidden">
        <Button
          variant="outline"
          size="icon"
          onClick={() => setSidebarOpen(!sidebarOpen)}
          className="bg-blue-900 text-white hover:bg-blue-800 hover:text-white"
        >
          <Menu className="h-5 w-5" />
        </Button>
      </div>

      {/* Overlay for mobile */}
      {sidebarOpen && (
        <div
          className="fixed inset-0 z-30 bg-black/50 md:hidden"
          onClick={() => setSidebarOpen(false)}
        />
      )}

      {/* Sidebar */}
      <aside
        className={`fixed inset-y-0 left-0 z-40 w-64 bg-blue-800 transition-transform duration-300 ease-in-out ${
          sidebarOpen ? "translate-x-0" : "-translate-x-full"
        } md:translate-x-0`}
      >
        {/* Close button - visible on mobile only */}
        <button
          onClick={() => setSidebarOpen(false)}
          className="absolute right-4 top-4 text-white md:hidden"
        >
          <X className="h-5 w-5" />
        </button>

        <div className="flex h-full flex-col">
          <div className="flex items-center justify-center p-4">
            <h2 className="text-xl font-bold text-white">Moderator Panel</h2>
          </div>

          <ul className="flex-1 space-y-1 p-4">
            <li>
              <Link
                href="/moderator"
                className={`mt-2 flex items-center rounded-lg px-4 py-2 ${
                  isActive("/moderator")
                    ? "bg-white text-black"
                    : "text-white hover:bg-white/10"
                }`}
              >
                <LayoutDashboard className="mr-3 h-5 w-5" />
                <span>Dashboard</span>
              </Link>
            </li>
            {/* If you want to add another nav item, just add it like this: */}
            {/* Example: 
            <li>
              <Link
              href="/moderator/users"
              className={`flex items-center rounded-lg px-4 py-2 ${
                isActive("/moderator/users")
                ? "bg-white text-black"
                : "text-white hover:bg-white/10"
              }`}
              >
              <Users className="mr-3 h-5 w-5" />
              <span>Users</span>
              </Link>
            </li>
            */}
          </ul>

          <div className="border-t border-white/10 p-4">
            <ul className="space-y-1">
              <li>
                <Link
                  href="/settings"
                  className={`flex items-center rounded-lg px-4 py-2 text-sm ${
                    isActive("/settings")
                      ? "bg-white text-black"
                      : "text-white hover:bg-white/10"
                  }`}
                >
                  <Settings className="mr-3 h-4 w-4" />
                  <span>Account Settings</span>
                </Link>
              </li>
              <li className="mt-2">
                <Button
                  onClick={logoutHandler}
                  type="submit"
                  className="flex w-full items-center justify-center gap-2 rounded-lg bg-white text-black hover:bg-white/90"
                >
                  <LogOut className="h-4 w-4" />
                  <span>Logout</span>
                </Button>
              </li>
            </ul>
          </div>
        </div>
      </aside>
    </>
  );
};

export default ModeratorSideBar;
