"use client";
import { useState, useEffect } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { FileText, Moon, Sun } from "lucide-react";
import { FaLock, FaChevronDown, FaChevronUp } from "react-icons/fa";
import { useTheme } from "../context/ThemeContext";

const Sidebar = ({ sidebarOpen, setSidebarOpen, isCollapsed }) => {
  const pathname = usePathname();
  const router = useRouter();
  const { darkMode, toggleDarkMode } = useTheme();
  const [openMenus, setOpenMenus] = useState({
    authentication: false
  });

  const isActive = (href) => pathname === href;

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

  const closeSidebarOnMobile = () => {
    if (window.innerWidth < 1024) {
      setSidebarOpen(false);
    }
  };
  const handleLogout = () => {
    localStorage.removeItem("token"); // or account.deleteSession("current") if using Appwrite
    router.push("/signup");
  };
  // ---------------logo handling in dark mode-----------------------
  // Create a separate LogoImage component for better error handling
  function LogoImage({ darkSrc, lightSrc, darkMode, className, alt }) {
    const [imgSrc, setImgSrc] = useState(darkMode ? darkSrc : lightSrc);
    const [errored, setErrored] = useState(false);

    useEffect(() => {
      setImgSrc(darkMode ? darkSrc : lightSrc);
      setErrored(false); // Reset error state when mode changes
    }, [darkMode, darkSrc, lightSrc]);

    const handleError = () => {
      if (!errored) {
        // Try falling back to opposite mode's image
        setImgSrc(darkMode ? lightSrc : darkSrc);
        setErrored(true);
      } else {
        // Ultimate fallback to placeholder
        setImgSrc('/images/logo/placeholder.svg');
      }
    };

    return (
      <img
        src={imgSrc}
        alt={alt}
        className={className}
        onError={handleError}
        loading="lazy"
      />
    );
  }
  // ----------------------------------------

  return (
    <aside
      className={`fixed lg:relative z-50 h-screen transition-all duration-300 ${darkMode ? 'bg-gray-800 text-gray-200' : 'bg-white text-gray-900'
        } transform ${sidebarOpen ? "translate-x-0" : "-translate-x-full lg:translate-x-0"
        } ${isCollapsed ? 'lg:w-20' : 'lg:w-64'}`}
    >
      <div className="h-full flex flex-col border-r border-gray-200 p-4 overflow-y-auto scrollbar-hide">
        {/* Logo Section */}
        

        {/* MENU section - Only show when not collapsed */}
        {!isCollapsed && (
          <h3 className={`text-xs sm:text-sm font-semibold mt-4 ${darkMode ? 'text-gray-400' : 'text-gray-500'
            }`}>
            MENU
          </h3>
        )}

        {/* Navigation Links */}
        <nav className="flex flex-col gap-1 sm:gap-2">
          {/* Dashboard Link */}
          <Link
            href="/dashboard"
            className={`flex items-center gap-2 p-3 rounded-md text-sm font-semibold transition-colors ${isActive("/dashboard")
                ? darkMode
                  ? "bg-blue-900 text-blue-200"
                  : "bg-blue-100 text-blue-800"
                : darkMode
                  ? "hover:bg-gray-700 text-gray-200"
                  : "hover:bg-gray-200"
              } ${isCollapsed ? 'justify-center' : ''}`}
            onClick={closeSidebarOnMobile}
          >
            <img
              src={darkMode ? "/images/icons/grid.svg" : "/images/icons/grid.svg"}
              alt="Dashboard"
              className={`w-5 ${darkMode ? 'filter brightness-0 invert' : ''}`}
              onError={(e) => {
                e.target.src = darkMode ? "/images/icons/grid.svg" : "/images/icons/grid.svg";
                e.target.className = 'w-5'; // Remove filter if fallback
              }}
            />
            {!isCollapsed && "Dashboard"}
          </Link>
          {/* -----------singleBooking/Add token-------------- */}
          <Link
            href="/pages/SingleBooking"
            className={`flex items-center gap-2 p-3 rounded-md text-sm font-semibold transition-colors ${isActive("/pages/UserProfile")
              ? darkMode
                ? "bg-blue-900 text-blue-200"
                : "bg-blue-100 text-blue-800"
              : darkMode
                ? "hover:bg-gray-700"
                : "hover:bg-gray-200"
              } ${isCollapsed ? 'justify-center' : ''}`}
            onClick={closeSidebarOnMobile}
          >
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" className="size-6">
              <path strokeLinecap="round" strokeLinejoin="round" d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10"></path>
            </svg>
            {!isCollapsed && "Add Token"}
          </Link>


          {/* -------------multibooking--------- */}
          <Link
            href="/pages/MultiBooking"
            className={`flex items-center gap-2 p-3 rounded-md text-sm font-semibold transition-colors ${isActive("/pages/UserProfile")
              ? darkMode
                ? "bg-blue-900 text-blue-200"
                : "bg-blue-100 text-blue-800"
              : darkMode
                ? "hover:bg-gray-700"
                : "hover:bg-gray-200"
              } ${isCollapsed ? 'justify-center' : ''}`}
            onClick={closeSidebarOnMobile}
          >
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" className="size-6">
              <path strokeLinecap="round" strokeLinejoin="round" d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10"></path>
            </svg>
            {!isCollapsed && "Add Multiple Tokens"}
          </Link>



          {/* Done tokens Link */}
          <Link
            href="/pages/done"
            className={`flex items-center gap-2 p-3 rounded-md text-sm font-semibold transition-colors ${isActive("/pages/CustomReport")
              ? darkMode
                ? "bg-blue-900 text-blue-200"
                : "bg-blue-100 text-blue-800"
              : darkMode
                ? "hover:bg-gray-700"
                : "hover:bg-gray-200"
              } ${isCollapsed ? 'justify-center' : ''}`}
            onClick={closeSidebarOnMobile}
          >
            <FileText size={18} className="w-5" />
            {!isCollapsed && "Done List"}
          </Link>



          {/* Missed tokens Link */}
          <Link
            href="/pages/missed"
            className={`flex items-center gap-2 p-3 rounded-md text-sm font-semibold transition-colors ${isActive("/pages/CustomReport")
              ? darkMode
                ? "bg-blue-900 text-blue-200"
                : "bg-blue-100 text-blue-800"
              : darkMode
                ? "hover:bg-gray-700"
                : "hover:bg-gray-200"
              } ${isCollapsed ? 'justify-center' : ''}`}
            onClick={closeSidebarOnMobile}
          >
            <FileText size={18} className="w-5" />
            {!isCollapsed && "Missed List"}
          </Link>
          {/* -----------------------Entries-------------------------------------------- */}

          {/* User Profile Link */}
          {/* <Link
            href="/pages/entries"
            className={`flex items-center gap-2 p-3 rounded-md text-sm font-semibold transition-colors ${isActive("/pages/UserProfile")
              ? darkMode
                ? "bg-blue-900 text-blue-200"
                : "bg-blue-100 text-blue-800"
              : darkMode
                ? "hover:bg-gray-700"
                : "hover:bg-gray-200"
              } ${isCollapsed ? 'justify-center' : ''}`}
            onClick={closeSidebarOnMobile}
          >
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" className="size-6">
              <path strokeLinecap="round" strokeLinejoin="round" d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10"></path>
            </svg>
            {!isCollapsed && "Entries"}
          </Link> */}

          {/* ------------staffBooking----------------
          <Link
            href="/pages/StaffBooking"
            className={`flex items-center gap-2 p-3 rounded-md text-sm font-semibold transition-colors ${isActive("/pages/UserProfile")
              ? darkMode
                ? "bg-blue-900 text-blue-200"
                : "bg-blue-100 text-blue-800"
              : darkMode
                ? "hover:bg-gray-700"
                : "hover:bg-gray-200"
              } ${isCollapsed ? 'justify-center' : ''}`}
            onClick={closeSidebarOnMobile}
          >
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" className="size-6">
              <path strokeLinecap="round" strokeLinejoin="round" d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10"></path>
            </svg>
            {!isCollapsed && "StaffBooking"}
          </Link> */}
          {/* ------------------------Setting--------------------------------- */}
          <Link
            href="/pages/setting"
            className={`flex items-center gap-2 p-3 rounded-md text-sm font-semibold transition-colors ${isActive("/pages/UserProfile")
              ? darkMode
                ? "bg-blue-900 text-blue-200"
                : "bg-blue-100 text-blue-800"
              : darkMode
                ? "hover:bg-gray-700"
                : "hover:bg-gray-200"
              } ${isCollapsed ? 'justify-center' : ''}`}
            onClick={closeSidebarOnMobile}
          >
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor" className="size-6">
              <path strokeLinecap="round" strokeLinejoin="round" d="M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.325.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 0 1 1.37.49l1.296 2.247a1.125 1.125 0 0 1-.26 1.431l-1.003.827c-.293.241-.438.613-.43.992a7.723 7.723 0 0 1 0 .255c-.008.378.137.75.43.991l1.004.827c.424.35.534.955.26 1.43l-1.298 2.247a1.125 1.125 0 0 1-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.47 6.47 0 0 1-.22.128c-.331.183-.581.495-.644.869l-.213 1.281c-.09.543-.56.94-1.11.94h-2.594c-.55 0-1.019-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 0 1-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 0 1-1.369-.49l-1.297-2.247a1.125 1.125 0 0 1 .26-1.431l1.004-.827c.292-.24.437-.613.43-.991a6.932 6.932 0 0 1 0-.255c.007-.38-.138-.751-.43-.992l-1.004-.827a1.125 1.125 0 0 1-.26-1.43l1.297-2.247a1.125 1.125 0 0 1 1.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.086.22-.128.332-.183.582-.495.644-.869l.214-1.28Z"></path>
              <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z"></path>
            </svg>
            {!isCollapsed && "Setting"}
          </Link>
          {/* ---------------------------------------------------------------------- */}


          {/* Custom Report Link */}
          {/* <Link
            href="/pages/CustomReport"
            className={`flex items-center gap-2 p-3 rounded-md text-sm font-semibold transition-colors ${isActive("/pages/CustomReport")
                ? darkMode
                  ? "bg-blue-900 text-blue-200"
                  : "bg-blue-100 text-blue-800"
                : darkMode
                  ? "hover:bg-gray-700"
                  : "hover:bg-gray-200"
              } ${isCollapsed ? 'justify-center' : ''}`}
            onClick={closeSidebarOnMobile}
          >
            <FileText size={18} className="w-5" />
            {!isCollapsed && "Custom Report"}
          </Link> */}

          {/* logout Link */}
          <div
            onClick={() => {
              handleLogout();
              closeSidebarOnMobile();
            }}
            className={`cursor-pointer flex items-center gap-2 p-3 rounded-md text-sm font-semibold transition-colors 
          ${isActive("/pages/reports")
                ? darkMode
                  ? "bg-blue-900 text-blue-200"
                  : "bg-blue-100 text-blue-800"
                : darkMode
                  ? "hover:bg-gray-700"
                  : "hover:bg-gray-200"
              } ${isCollapsed ? "justify-center" : ""}`}
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 24 24"
              strokeWidth="1.5"
              stroke="currentColor"
              className="size-6"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M8.25 9V5.25A2.25 2.25 0 0 1 10.5 3h6a2.25 2.25 0 0 1 2.25 2.25v13.5A2.25 2.25 0 0 1 16.5 21h-6a2.25 2.25 0 0 1-2.25-2.25V15m-3 0-3-3m0 0 3-3m-3 3H15"
              />
            </svg>
            {!isCollapsed && "logout"}
          </div>
          {/* Authentication Dropdown - Hidden when collapsed */}
          {/* {!isCollapsed && (
            <div className="flex flex-col">
              <button
                onClick={() => toggleMenu("authentication")}
                className={`flex items-center justify-between gap-2 p-3 rounded-md text-sm font-semibold transition-colors ${openMenus.authentication
                  ? darkMode
                    ? "bg-blue-900 text-blue-200"
                    : "bg-blue-100 text-blue-800"
                  : darkMode
                    ? "hover:bg-gray-700"
                    : "hover:bg-gray-200"
                  }`}
              >
                <div className="flex items-center gap-2">
                  <FaLock size={16} className="w-5" />
                  Authentication
                </div>
                {openMenus.authentication ? (
                  <FaChevronUp size={14} />
                ) : (
                  <FaChevronDown size={14} />
                )}
              </button>

              {openMenus.authentication && (
                <div className={`ml-6 flex flex-col gap-1 py-1 ${darkMode ? 'bg-gray-700' : 'bg-gray-50'
                  } rounded-md`}>
                  <Link
                    href="/pages/SignUpPage"
                    className={`flex items-center gap-2 p-3 rounded-md font-semibold text-sm transition-colors ${isActive("/pages/SignUpPage")
                      ? darkMode
                        ? "bg-blue-900 text-blue-200"
                        : "bg-blue-100 text-blue-800"
                      : darkMode
                        ? "hover:bg-gray-600"
                        : "hover:bg-gray-200"
                      }`}
                    onClick={closeSidebarOnMobile}
                  >
                    Sign Up
                  </Link>
                  <Link
                    href="/pages/SignInPage"
                    className={`flex items-center gap-2 p-3 rounded-md text-sm font-semibold transition-colors ${isActive("/pages/SignInPage")
                      ? darkMode
                        ? "bg-blue-900 text-blue-200"
                        : "bg-blue-100 text-blue-800"
                      : darkMode
                        ? "hover:bg-gray-600"
                        : "hover:bg-gray-200"
                      }`}
                    onClick={closeSidebarOnMobile}
                  >
                    Sign In
                  </Link>
                </div>
              )}
            </div>
          )} */}
        </nav>


      </div>
    </aside>
  );
};

export default Sidebar;