"use client"

import { useState, useEffect } from "react"
import { usePathname } from "next/navigation"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { createClient } from "@/lib/supabase/client"
import type { User } from "@/lib/supabase/database.types"
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
} from "@/components/ui/sidebar"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
import {
  Calendar,
  ChevronUp,
  LogOut,
  Settings,
  MessageSquare,
  LayoutDashboard,
  BarChart2,
} from "lucide-react"

const mainNavItems = [
  {
    title: "Nueva Reserva",
    url: "/dashboard",
    icon: LayoutDashboard,
  },
  {
    title: "Mis Reservas",
    url: "/reservations/my-reservations",
    icon: Calendar,
  },
  {
    title: "Sammy",
    url: "/sammy",
    icon: MessageSquare,
  },
]

const adminNavItems = [
  {
    title: "Configuracion",
    url: "/admin",
    icon: Settings,
    isActive: (pathname: string) =>
      pathname.startsWith("/admin") && !pathname.startsWith("/admin/metrics"),
  },
  {
    title: "Metricas",
    url: "/admin/metrics",
    icon: BarChart2,
    isActive: (pathname: string) => pathname.startsWith("/admin/metrics"),
  },
]

interface AppSidebarProps {
  user: User | null
}

export function AppSidebar({ user }: AppSidebarProps) {
  const pathname = usePathname()
  const router = useRouter()
  const isAdmin = user?.role === "admin"
  const [mounted, setMounted] = useState(false)
  useEffect(() => setMounted(true), [])

  const handleSignOut = async () => {
    const supabase = createClient()
    await supabase.auth.signOut()
    router.push("/auth/login")
  }

  const getInitials = (name: string | null | undefined, email: string) => {
    if (name) {
      return name.split(" ").map((n) => n[0]).join("").toUpperCase().slice(0, 2)
    }
    return email.slice(0, 2).toUpperCase()
  }

  return (
    <Sidebar className="border-r border-[var(--ds-neutral-200)]" collapsible="offcanvas">
      <SidebarContent>
        <SidebarGroup className="px-[var(--ds-space-2x)] pt-[var(--ds-space-3x)] pb-[var(--ds-space-15x)] gap-[var(--ds-space-05x)]">
          <SidebarGroupLabel className="ds-type-global-xxs ds-type-semibold uppercase tracking-[0.4px] text-[var(--ds-text-neutral-lighter)]">
            Menu Principal
          </SidebarGroupLabel>
          <SidebarGroupContent>
            <SidebarMenu className="gap-[var(--ds-space-1x)]">
              {mainNavItems.map((item) => (
                <SidebarMenuItem key={item.title}>
                  <SidebarMenuButton
                    asChild
                    isActive={pathname === item.url}
                    className="ds-type-global-xs rounded-[var(--ds-radius-m)] text-[var(--ds-text-neutral-default)] h-10 px-3"
                  >
                    <Link href={item.url}>
                      <item.icon />
                      <span>{item.title}</span>
                    </Link>
                  </SidebarMenuButton>
                </SidebarMenuItem>
              ))}
            </SidebarMenu>
          </SidebarGroupContent>
        </SidebarGroup>

        {isAdmin && (
          <SidebarGroup className="px-[var(--ds-space-2x)] py-[var(--ds-space-15x)]">
            <SidebarGroupLabel className="ds-type-global-xxs ds-type-semibold uppercase tracking-[0.4px] text-[var(--ds-text-neutral-lighter)]">
              Administrador
            </SidebarGroupLabel>
            <SidebarGroupContent>
              <SidebarMenu className="gap-[var(--ds-space-1x)]">
                {adminNavItems.map((item) => (
                  <SidebarMenuItem key={item.title}>
                    <SidebarMenuButton
                      asChild
                      isActive={item.isActive(pathname)}
                      className="ds-type-global-xs rounded-[var(--ds-radius-m)] text-[var(--ds-text-neutral-default)] h-10 px-3"
                    >
                      <Link href={item.url}>
                        <item.icon />
                        <span>{item.title}</span>
                      </Link>
                    </SidebarMenuButton>
                  </SidebarMenuItem>
                ))}
              </SidebarMenu>
            </SidebarGroupContent>
          </SidebarGroup>
        )}
      </SidebarContent>

      <SidebarFooter className="border-t border-[var(--ds-neutral-200)] p-[var(--ds-space-2x)]">
        <SidebarMenu>
          <SidebarMenuItem>
            {mounted ? (
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <SidebarMenuButton
                    size="lg"
                    className="h-[56px] rounded-[var(--ds-radius-m)] data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
                  >
                    <Avatar className="h-[var(--ds-space-4x)] w-[var(--ds-space-4x)] rounded-[var(--ds-radius-m)]">
                      <AvatarFallback className="rounded-[var(--ds-radius-m)] bg-[var(--ds-blueprimary-100)] text-[var(--ds-blueprimary-800)]">
                        {getInitials(user?.full_name, user?.email || "")}
                      </AvatarFallback>
                    </Avatar>
                    <div className="grid flex-1 text-left text-sm leading-tight">
                      <span className="truncate ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                        {user?.full_name || user?.email?.split("@")[0]}
                      </span>
                      <span className="truncate ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                        {user?.email}
                      </span>
                    </div>
                    <ChevronUp className="ml-auto size-4" />
                  </SidebarMenuButton>
                </DropdownMenuTrigger>
                <DropdownMenuContent
                  className="w-[--radix-dropdown-menu-trigger-width] min-w-56 rounded-[var(--ds-radius-m)] border-[var(--ds-neutral-200)] shadow-[var(--ds-shadow-8dp)]"
                  side="top"
                  align="end"
                  sideOffset={4}
                >
                  <DropdownMenuItem className="gap-2 ds-type-global-xs" onClick={handleSignOut}>
                    <LogOut className="size-4" />
                    <span>Cerrar sesion</span>
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            ) : (
              <div className="flex w-full items-center gap-2 overflow-hidden rounded-[var(--ds-radius-m)] p-2 h-[56px]" aria-hidden>
                <Avatar className="h-[var(--ds-space-4x)] w-[var(--ds-space-4x)] shrink-0 rounded-[var(--ds-radius-m)]">
                  <AvatarFallback className="rounded-[var(--ds-radius-m)] bg-[var(--ds-blueprimary-100)] text-[var(--ds-blueprimary-800)]">
                    {getInitials(user?.full_name, user?.email || "")}
                  </AvatarFallback>
                </Avatar>
                <div className="grid min-w-0 flex-1 text-left leading-tight">
                  <span className="truncate ds-type-global-xs ds-type-semibold text-[var(--ds-text-neutral-default)]">
                    {user?.full_name || user?.email?.split("@")[0]}
                  </span>
                  <span className="truncate ds-type-global-xxs text-[var(--ds-text-neutral-lighter)]">
                    {user?.email}
                  </span>
                </div>
                <ChevronUp className="ml-auto size-4 shrink-0" />
              </div>
            )}
          </SidebarMenuItem>
        </SidebarMenu>
      </SidebarFooter>
    </Sidebar>
  )
}
