"use client";

import { removeAuthToken, removeRefAuthToken } from "@/shared/lib/authCookies";
import { cn } from "@/shared/lib/utils";
import { Button } from "@/shared/ui/button";
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
} from "@/shared/ui/sheet";
import LangToggle from "@/widgets/lang-toggle/ui/lang-toggle";
import { useQueryClient } from "@tanstack/react-query";
import {
  Briefcase,
  Building2,
  ChevronDown,
  ChevronRight,
  HelpCircle,
  LogOut,
  Menu,
  MessageSquare,
  Newspaper,
  Plane,
  Settings,
  Users,
  Wallet,
} from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { useLocation, useNavigate } from "react-router-dom";
import { toast } from "sonner";

type Role =
  | "superuser"
  | "admin"
  | "moderator"
  | "tour_admin"
  | "buxgalter"
  | "operator"
  | "user";

interface SidebarProps {
  role: Role;
}

const MENU_ITEMS = [
  {
    label: "Foydalanuvchilar",
    icon: Users,
    path: "/user",
    roles: ["moderator", "admin", "superuser", "operator"],
  },
  {
    label: "Profile",
    icon: Users,
    path: "/profile",
    roles: ["tour_admin"],
  },
  {
    label: "Tur firmalar",
    icon: Building2,
    path: "/agencies",
    roles: ["moderator", "admin", "superuser", "operator"],
  },
  {
    label: "Xodimlar",
    icon: Briefcase,
    path: "/employees",
    roles: ["moderator", "admin", "superuser"],
  },
  {
    label: "Bronlar",
    icon: Wallet,
    path: "/finance",
    roles: ["moderator", "admin", "superuser", "buxgalter", "tour_admin"],
  },
  {
    label: "Turlar",
    icon: Plane,
    path: "/tours",
    roles: ["moderator", "admin", "superuser", "tour_admin"],
    children: [
      { label: "Turlar", path: "/tours" },
      {
        label: "Tur sozlamalari",
        path: "/tours/setting",
        roles: ["moderator", "admin", "superuser"],
      },
    ],
  },
  {
    label: "Yangiliklar",
    icon: Newspaper,
    path: "/news",
    roles: ["moderator", "admin", "superuser"],
    children: [
      { label: "Yangiliklar", path: "/news" },
      { label: "Kategoriya", path: "/news/categories" },
    ],
  },
  {
    label: "FAQ",
    icon: MessageSquare,
    path: "/faq",
    roles: ["moderator", "admin", "superuser"],
    children: [
      { label: "Savollar ro'yxati", path: "/faq" },
      { label: "Savollar kategoriyasi", path: "/faq/categories" },
    ],
  },
  {
    label: "Arizalar",
    icon: HelpCircle,
    path: "/support",
    roles: ["moderator", "admin", "superuser", "tour_admin", "operator"],
    children: [
      {
        label: "Agentlik arizalari",
        path: "/support/tours",
        roles: ["moderator", "admin", "superuser"],
      },
      {
        label: "Yordam arizalari",
        path: "/support/user",
        roles: [
          "moderator",
          "admin",
          "superuser",
          "tour_admin",
          "operator",
          "buxgalter",
        ],
      },
    ],
  },
  {
    label: "Sayt sozlamalari",
    icon: Settings,
    path: "/tour-settings",
    roles: ["moderator", "admin", "superuser"],
    children: [
      { label: "Sayt SEOsi", path: "/site-seo/" },
      { label: "Offerta", path: "/site-pages/" },
      { label: "Yordam pagelari", path: "/site-help/" },
      { label: "Sayt sozlamalari", path: "/site-settings/" },
      { label: "Sayt uchun Banner", path: "/site-banner/" },
    ],
  },
  {
    label: "Pul olish so'rovlari",
    icon: Wallet,
    path: "/withdraw/list",
    roles: ["buxgalter", "moderator", "tour_admin"],
  },
];

export function Sidebar({ role }: SidebarProps) {
  const navigate = useNavigate();
  const { t } = useTranslation();
  const location = useLocation();
  const queryClient = useQueryClient();
  const [isSheetOpen, setIsSheetOpen] = useState(false);

  const visibleMenu = useMemo(() => {
    return MENU_ITEMS.filter((item) => item.roles.includes(role)).map(
      (item) => ({
        ...item,
        children: item.children
          ? item.children.filter(
              (child) => !child.roles || child.roles.includes(role),
            )
          : [],
      }),
    );
  }, [role]);

  const [active, setActive] = useState<string>(location.pathname);
  const [openMenus, setOpenMenus] = useState<string[]>([]);

  useEffect(() => {
    setActive(location.pathname);
  }, [location.pathname]);

  const handleClick = (path: string) => {
    setActive(path);
    navigate(path);
    setIsSheetOpen(false);
  };

  const toggleSubMenu = (label: string) => {
    setOpenMenus((prev) =>
      prev.includes(label) ? prev.filter((m) => m !== label) : [...prev, label],
    );
  };

  const handleLogout = () => {
    removeAuthToken();
    removeRefAuthToken();
    queryClient.clear();
    toast.success(t("Tizimdan chiqdingiz"));
    navigate("/auth/login");
  };

  const MenuList = (
    <div className="flex flex-col h-full">
      <ul className="p-2 space-y-1 flex-1 overflow-y-auto scrollbar-thin scrollbar-thumb-gray-600 scrollbar-track-gray-800 hover:scrollbar-thumb-gray-500">
        {visibleMenu.map(({ label, icon: Icon, path, children }) => {
          const isActive = active.startsWith(path);
          const isOpen = openMenus.includes(label);
          const hasChildren = children?.length > 0;

          return (
            <li key={path}>
              <div
                className={cn(
                  "w-full flex items-center justify-between gap-2 px-2 py-3 rounded-md cursor-pointer transition text-md font-medium",
                  isActive
                    ? "bg-gray-600 text-white"
                    : "text-gray-400 hover:bg-gray-700 hover:text-white",
                )}
                onClick={() =>
                  hasChildren ? toggleSubMenu(label) : handleClick(path)
                }
              >
                <div className="flex items-center gap-2">
                  <Icon className="w-5 h-5" />
                  {t(label)}
                </div>
                {hasChildren && (
                  <span className="transition-transform">
                    {isOpen ? (
                      <ChevronDown className="w-4 h-4" />
                    ) : (
                      <ChevronRight className="w-4 h-4" />
                    )}
                  </span>
                )}
              </div>

              {hasChildren && isOpen && (
                <ul className="ml-6 mt-1 space-y-1 border-l border-gray-700 pl-3">
                  {children.map((sub) => (
                    <li key={sub.path}>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleClick(sub.path)}
                        className={cn(
                          "w-full justify-start gap-2 text-sm !px-2 !py-2 cursor-pointer",
                          active === sub.path
                            ? "bg-gray-700 text-white"
                            : "text-gray-400 hover:text-white hover:bg-gray-800",
                        )}
                      >
                        {t(sub.label)}
                      </Button>
                    </li>
                  ))}
                </ul>
              )}
            </li>
          );
        })}
      </ul>
      <div className="border-t border-gray-700 mt-2 pt-3 px-2">
        <LangToggle />
      </div>
      <div className="border-t border-gray-700 mt-2 pt-3 px-2">
        <Button
          onClick={handleLogout}
          variant="ghost"
          className="w-full flex items-center justify-start gap-2 text-red-400 hover:bg-red-900/20 hover:text-red-300 mt-2"
        >
          <LogOut className="w-5 h-5" />
          <span>{t("Chiqish")}</span>
        </Button>
      </div>
    </div>
  );

  return (
    <div className="lg:border fixed max-lg:sticky overflow-y-auto sidebar-scroll">
      {/* Mobil versiya */}
      <div className="lg:hidden flex items-center justify-end bg-gray-900 p-4 sticky top-0 z-50">
        <Sheet open={isSheetOpen} onOpenChange={setIsSheetOpen}>
          <div className="flex gap-4">
            <LangToggle />
            <SheetTrigger asChild>
              <Button variant="outline" size="icon">
                <Menu className="w-5 h-5" />
              </Button>
            </SheetTrigger>
          </div>

          <SheetContent side="left" className="p-0 w-64 bg-gray-900">
            <SheetHeader className="p-4 border-b">
              <SheetTitle className="flex items-center gap-2">
                <img
                  src="/Logo_white.png"
                  width={120}
                  height={120}
                  alt="logo"
                />
              </SheetTitle>
            </SheetHeader>
            <nav className="h-full">{MenuList}</nav>
          </SheetContent>
        </Sheet>
      </div>

      {/* Desktop versiya */}
      <aside className="hidden bg-gray-900 lg:flex w-64 flex-col h-screen">
        <div className="flex items-center gap-2 p-4 border-b">
          <img src="/Logo_white.png" width={120} height={120} alt="logo" />
        </div>
        <nav className="flex-1">{MenuList}</nav>
      </aside>
    </div>
  );
}
