"use client"

import { useCallback, useEffect, useMemo, useState } from "react"
import { useRouter } from "next/navigation"
import {
  IconDotsVertical,
  IconLogout,
  IconNotification,
  IconUserCircle,
} from "@tabler/icons-react"
import { toast } from "sonner"

import {
  Avatar,
  AvatarFallback,
  AvatarImage,
} from "@/components/ui/avatar"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  useSidebar,
} from "@/components/ui/sidebar"
import { signOut, useAuth } from "@/lib/auth-client"

type NavUserProps = {
  user?: {
    name?: string | null
    email?: string | null
    avatarUrl?: string | null
  } | null
}

export function NavUser({ user }: NavUserProps) {
  const normalizedUser = user ?? { name: null, email: null, avatarUrl: null }
  const { isMobile } = useSidebar()
  const router = useRouter()
  const [isSigningOut, setIsSigningOut] = useState(false)
  const [isDesktopShell, setIsDesktopShell] = useState(false)
  const { session } = useAuth()
  const isMachineSession = (session?.user?.role ?? "").toLowerCase() === "machine"

  useEffect(() => {
    if (typeof window === "undefined") return
    setIsDesktopShell(Boolean((window as typeof window & { __TAURI__?: unknown }).__TAURI__))
  }, [])

  const initials = useMemo(() => {
    const source = normalizedUser.name?.trim() || normalizedUser.email?.trim() || ""
    if (!source) return "US"
    const parts = source.split(" ").filter(Boolean)
    const firstTwo = parts.slice(0, 2).map((part) => part[0]).join("")
    if (firstTwo) return firstTwo.toUpperCase()
    return source.slice(0, 2).toUpperCase()
  }, [normalizedUser.name, normalizedUser.email])

  const displayName = normalizedUser.name?.trim() || "Usuário"
  const displayEmail = normalizedUser.email?.trim() || "Sem e-mail definido"

  const handleProfile = useCallback(() => {
    router.push("/settings")
  }, [router])

  const handleNotifications = useCallback(() => {
    router.push("/settings/notifications")
  }, [router])

  const handleSignOut = useCallback(async () => {
    if (isSigningOut) return
    setIsSigningOut(true)
    try {
      await signOut()
      toast.success("Sessão encerrada.")
      router.replace("/login")
    } catch (error) {
      console.error("Erro ao encerrar sessão", error)
      toast.error("Não foi possível encerrar a sessão.")
    } finally {
      setIsSigningOut(false)
    }
  }, [isSigningOut, router])

  return (
    <SidebarMenu>
      <SidebarMenuItem>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <SidebarMenuButton
              size="lg"
              className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
            >
              <Avatar className="h-8 w-8 rounded-lg">
                <AvatarImage src={normalizedUser.avatarUrl ?? undefined} alt={displayName} />
                <AvatarFallback className="rounded-lg bg-neutral-200 text-neutral-700 font-medium">{initials}</AvatarFallback>
              </Avatar>
              <div className="grid flex-1 text-left text-sm leading-tight">
                <span className="truncate font-medium">{displayName}</span>
                <span className="text-muted-foreground truncate text-xs">
                  {displayEmail}
                </span>
              </div>
              <IconDotsVertical className="ml-auto size-4" />
            </SidebarMenuButton>
          </DropdownMenuTrigger>
          <DropdownMenuContent
            className="w-(--radix-dropdown-menu-trigger-width) min-w-56 rounded-lg"
            side={isMobile ? "bottom" : "right"}
            align="end"
            sideOffset={4}
          >
            <DropdownMenuLabel className="p-0 font-normal">
              <div className="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
                <Avatar className="h-8 w-8 rounded-lg">
                  <AvatarImage src={normalizedUser.avatarUrl ?? undefined} alt={displayName} />
                  <AvatarFallback className="rounded-lg bg-neutral-200 text-neutral-700 font-medium">{initials}</AvatarFallback>
                </Avatar>
                <div className="grid flex-1 text-left text-sm leading-tight">
                  <span className="truncate font-medium">{displayName}</span>
                  <span className="text-muted-foreground truncate text-xs">
                    {displayEmail}
                  </span>
                </div>
              </div>
            </DropdownMenuLabel>
            <DropdownMenuSeparator />
            <DropdownMenuGroup>
              <DropdownMenuItem
                onSelect={(event) => {
                  event.preventDefault()
                  handleProfile()
                }}
              >
                <IconUserCircle className="size-4" />
                <span>Meu perfil</span>
              </DropdownMenuItem>
              <DropdownMenuItem
                onSelect={(event) => {
                  event.preventDefault()
                  handleNotifications()
                }}
              >
                <IconNotification className="size-4" />
                <span>Notificações</span>
              </DropdownMenuItem>
            </DropdownMenuGroup>
            {!isDesktopShell && !isMachineSession ? (
              <>
                <DropdownMenuSeparator />
                <DropdownMenuItem
                  onSelect={(event) => {
                    event.preventDefault()
                    handleSignOut()
                  }}
                  disabled={isSigningOut}
                >
                  <IconLogout className="size-4" />
                  <span>{isSigningOut ? "Encerrando…" : "Encerrar sessão"}</span>
                </DropdownMenuItem>
              </>
            ) : null}
          </DropdownMenuContent>
        </DropdownMenu>
      </SidebarMenuItem>
    </SidebarMenu>
  )
}
