"use client"

import { useState } from "react"
import Link from "next/link"
import { usePathname, useRouter } from "next/navigation"
import { useDispatch } from "react-redux"
import {
  LayoutDashboardIcon,
  ShoppingBagIcon,
  CalendarIcon,
  UtensilsIcon,
  BoxIcon,
  SettingsIcon,
  ChevronDownIcon,
  BuildingIcon,
  UsersIcon,
  TagIcon,
  ListIcon,
  MenuIcon,
  XIcon,
  LogOutIcon,
} from "lucide-react"

import { cn } from "@/src/lib/utils"
import { useGetRestaurantInfoQuery, logout } from "@/src/state/auth"
import type { AppDispatch } from "@/src/state/store"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/src/components/ui/dialog"
import { Button } from "@/src/components/ui/button"

interface SubItem {
  label: string
  href: string
  icon: React.ReactNode
}

interface NavItem {
  label: string
  href?: string
  icon: React.ReactNode
  children?: SubItem[]
}

const NAV_ITEMS: NavItem[] = [
  {
    label: "Tableau de bord",
    href: "/home",
    icon: <LayoutDashboardIcon className="size-5" />,
  },
  {
    label: "Commandes",
    href: "/orders",
    icon: <ShoppingBagIcon className="size-5" />,
  },
  {
    label: "Calendrier",
    href: "/calendar",
    icon: <CalendarIcon className="size-5" />,
  },
  {
    label: "Menu",
    icon: <UtensilsIcon className="size-5" />,
    children: [
      { label: "Catégories", href: "/menu/categories", icon: <TagIcon className="size-4" /> },
      { label: "Articles", href: "/menu/items", icon: <ListIcon className="size-4" /> },
    ],
  },
  {
    label: "Inventaire",
    icon: <BoxIcon className="size-5" />,
    children: [
      { label: "Stocks", href: "/inventory/stocks", icon: <BoxIcon className="size-4" /> },
      { label: "Fournisseurs", href: "/inventory/suppliers", icon: <UsersIcon className="size-4" /> },
    ],
  },
  {
    label: "Paramètres",
    icon: <SettingsIcon className="size-5" />,
    children: [
      { label: "Profil entreprise", href: "/settings/profile", icon: <BuildingIcon className="size-4" /> },
      { label: "Gestion utilisateurs", href: "/settings/users", icon: <UsersIcon className="size-4" /> },
    ],
  },
]

export default function Sidebar() {
  const pathname = usePathname()
  const router = useRouter()
  const dispatch = useDispatch<AppDispatch>()
  const [isOpen, setIsOpen] = useState(false)
  const [logoutDialogOpen, setLogoutDialogOpen] = useState(false)
  const [openMenus, setOpenMenus] = useState<Record<string, boolean>>({})
  const { data } = useGetRestaurantInfoQuery()
  const restaurantName = data?.data?.restaurantName ?? "Bon Petit"

  function toggleMenu(label: string) {
    setOpenMenus((prev) => ({ ...prev, [label]: !prev[label] }))
  }

  function isActive(href: string) {
    return pathname === href || pathname.startsWith(href + "/")
  }

  function hasActiveChild(children: SubItem[]) {
    return children.some((c) => isActive(c.href))
  }

  function handleLogout() {
    dispatch(logout())
    router.replace("/signin")
  }

  return (
    <>
      <div className="md:hidden fixed top-4 left-4 z-50">
        <button
          onClick={() => setIsOpen(!isOpen)}
          className="p-2 rounded-lg bg-white border border-border text-foreground shadow-sm"
        >
          {isOpen ? <XIcon className="size-5" /> : <MenuIcon className="size-5" />}
        </button>
      </div>

      {isOpen && (
        <div
          className="fixed inset-0 bg-black/50 md:hidden z-40"
          onClick={() => setIsOpen(false)}
        />
      )}

      <aside
        className={cn(
          "fixed md:relative inset-y-0 left-0 flex flex-col h-full w-[220px] bg-white border-r border-border overflow-y-auto transition-transform duration-300 md:translate-x-0 z-40",
          isOpen ? "translate-x-0" : "-translate-x-full",
        )}
      >
        <div className="flex h-16 shrink-0 items-center gap-3 px-4 border-b border-border">
          <div className="flex size-8 shrink-0 items-center justify-center rounded-full bg-primary">
            <UtensilsIcon className="size-4 text-white" />
          </div>
          <span className="text-base font-bold tracking-tight text-foreground truncate">
            {restaurantName}
          </span>
        </div>

        <nav className="flex-1 space-y-0.5 px-3 py-4">
          {NAV_ITEMS.map((item) => {
            const hasChildren = !!item.children?.length
            const isMenuOpen = openMenus[item.label]
            const active = item.href
              ? isActive(item.href)
              : hasChildren && hasActiveChild(item.children!)

            if (hasChildren) {
              return (
                <div key={item.label}>
                  <button
                    type="button"
                    onClick={() => toggleMenu(item.label)}
                    className={cn(
                      "flex w-full items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors",
                      active
                        ? "bg-primary text-white"
                        : "text-foreground/70 hover:bg-primary/10 hover:text-foreground",
                    )}
                  >
                    <span className="shrink-0">{item.icon}</span>
                    <span className="flex-1 text-left">{item.label}</span>
                    <ChevronDownIcon
                      className={cn(
                        "size-4 transition-transform duration-200",
                        isMenuOpen ? "rotate-180" : "",
                      )}
                    />
                  </button>

                  {isMenuOpen && (
                    <div className="ml-3 mt-0.5 space-y-0.5 border-l border-border pl-3">
                      {item.children!.map((child) => (
                        <Link
                          key={child.href}
                          href={child.href}
                          onClick={() => setIsOpen(false)}
                          className={cn(
                            "flex items-center gap-2.5 rounded-lg px-3 py-2 text-sm transition-colors",
                            isActive(child.href)
                              ? "bg-primary text-white font-medium"
                              : "text-foreground/60 hover:bg-primary/10 hover:text-foreground",
                          )}
                        >
                          {child.icon}
                          {child.label}
                        </Link>
                      ))}
                    </div>
                  )}
                </div>
              )
            }

            return (
              <Link
                key={item.href}
                href={item.href!}
                onClick={() => setIsOpen(false)}
                className={cn(
                  "flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors",
                  active
                    ? "bg-primary text-white"
                    : "text-foreground/70 hover:bg-primary/10 hover:text-foreground",
                )}
              >
                <span className="shrink-0">{item.icon}</span>
                <span>{item.label}</span>
              </Link>
            )
          })}
        </nav>

        <div className="px-3 pb-4">
          <button
            type="button"
            onClick={() => setLogoutDialogOpen(true)}
            className="flex w-full items-center cursor-pointer gap-3 px-3 py-2.5 rounded-lg text-sm font-medium text-foreground/70 hover:bg-primary/10 hover:text-foreground transition-colors"
          >
            <LogOutIcon className="size-5 shrink-0" />
            <span>Se déconnecter</span>
          </button>
        </div>
      </aside>

      <Dialog open={logoutDialogOpen} onOpenChange={setLogoutDialogOpen}>
        <DialogContent className="max-w-[534px]">
          <DialogHeader>
            <DialogTitle>Se déconnecter</DialogTitle>
            <DialogDescription>
              Êtes-vous sûr de vouloir vous déconnecter ? Vous devrez vous reconnecter pour accéder à votre espace restaurant.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setLogoutDialogOpen(false)}>
              Annuler
            </Button>
            <Button onClick={handleLogout}>
              Se déconnecter
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  )
}
