"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { useTheme } from "@/components/theme-provider"
import {
  ChevronsUpDownIcon,
  LogOutIcon,
  MonitorIcon,
  MoonIcon,
  PaletteIcon,
  SettingsIcon,
  SunIcon,
} from "lucide-react"

import { cn } from "@/lib/utils"
import {
  ensureAuthConfig,
  getClaims,
  isAuthEnabled,
  redirectToPortalLogout,
} from "@/lib/auth"
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  useSidebar,
} from "@/components/ui/sidebar"

/** Sidebar footer account menu — app-shell-1 NavUser. @see https://reui.io/preview/base/app-shell-1 */

const THEMES = [
  {
    value: "light" as const,
    label: "Светлая",
    icon: <SunIcon className="size-3.5" aria-hidden />,
  },
  {
    value: "dark" as const,
    label: "Тёмная",
    icon: <MoonIcon className="size-3.5" aria-hidden />,
  },
  {
    value: "system" as const,
    label: "Системная",
    icon: <MonitorIcon className="size-3.5" aria-hidden />,
  },
]

function ThemeSegmentedToggle() {
  const { theme, setTheme } = useTheme()
  const [mounted, setMounted] = useState(false)

  useEffect(() => {
    setMounted(true)
  }, [])

  const currentTheme = mounted ? (theme ?? "system") : "system"

  return (
    <div
      role="radiogroup"
      aria-label="Тема"
      className="bg-muted/60 inline-flex items-center gap-0.5 rounded-full p-0.5"
      onClick={(e) => e.stopPropagation()}
      onPointerDown={(e) => e.stopPropagation()}
    >
      {THEMES.map(({ value, label, icon }) => {
        const isActive = currentTheme === value
        return (
          <Button
            key={value}
            type="button"
            role="radio"
            aria-checked={isActive}
            aria-label={label}
            variant="ghost"
            size="icon-xs"
            onClick={() => setTheme(value)}
            className={cn(
              "rounded-full",
              isActive
                ? "bg-background text-foreground shadow-sm"
                : "text-muted-foreground hover:text-foreground",
            )}
          >
            {icon}
          </Button>
        )
      })}
    </div>
  )
}

function initials(name: string, email: string): string {
  const base = (name || email || "?").trim()
  const parts = base.split(/\s+/).filter(Boolean)
  if (parts.length >= 2) {
    return (parts[0]![0]! + parts[1]![0]!).toUpperCase()
  }
  return base.slice(0, 2).toUpperCase()
}

export function NavUser() {
  const { isMobile } = useSidebar()
  const [name, setName] = useState("Оператор")
  const [email, setEmail] = useState("локальный доступ")
  const [showLogout, setShowLogout] = useState(false)

  useEffect(() => {
    void ensureAuthConfig().then(() => {
      const claims = getClaims()
      if (claims) {
        setName(claims.name || claims.email || "Пользователь")
        setEmail(claims.email || "")
        setShowLogout(isAuthEnabled())
      } else if (isAuthEnabled()) {
        setName("Сессия")
        setEmail("требуется вход")
        setShowLogout(true)
      }
    })
  }, [])

  const fallback = initials(name, email)

  return (
    <SidebarMenu>
      <SidebarMenuItem>
        <DropdownMenu>
          <DropdownMenuTrigger
            render={
              <SidebarMenuButton
                size="lg"
                className="data-popup-open:bg-sidebar-accent data-popup-open:text-sidebar-accent-foreground"
              />
            }
          >
            <Avatar className="size-8 rounded-lg">
              <AvatarFallback className="rounded-lg text-xs">{fallback}</AvatarFallback>
            </Avatar>
            <div className="grid flex-1 text-left text-sm leading-tight">
              <span className="truncate font-semibold">{name}</span>
              <span className="truncate text-xs text-muted-foreground">{email}</span>
            </div>
            <ChevronsUpDownIcon className="ml-auto size-4" />
          </DropdownMenuTrigger>
          <DropdownMenuContent
            className="w-(--anchor-width) min-w-56 rounded-lg"
            side={isMobile ? "bottom" : "right"}
            align="end"
            sideOffset={4}
          >
            <DropdownMenuGroup>
              <DropdownMenuLabel className="flex items-center gap-2 py-2 font-normal text-foreground">
                <Avatar className="size-8 rounded-lg">
                  <AvatarFallback className="rounded-lg text-xs">{fallback}</AvatarFallback>
                </Avatar>
                <div className="grid min-w-0 flex-1 text-left text-sm leading-tight">
                  <span className="truncate font-semibold">{name}</span>
                  <span className="truncate text-xs text-muted-foreground">{email}</span>
                </div>
              </DropdownMenuLabel>
            </DropdownMenuGroup>

            <DropdownMenuSeparator />

            <DropdownMenuGroup>
              <DropdownMenuItem render={<Link href="/settings" />}>
                <SettingsIcon aria-hidden />
                Настройки
              </DropdownMenuItem>
              <DropdownMenuItem className="cursor-default focus:bg-transparent">
                <PaletteIcon aria-hidden />
                Тема
                <div className="ml-auto">
                  <ThemeSegmentedToggle />
                </div>
              </DropdownMenuItem>
              {showLogout ? (
                <DropdownMenuItem onClick={() => redirectToPortalLogout()}>
                  <LogOutIcon aria-hidden />
                  Выйти
                </DropdownMenuItem>
              ) : null}
            </DropdownMenuGroup>
          </DropdownMenuContent>
        </DropdownMenu>
      </SidebarMenuItem>
    </SidebarMenu>
  )
}
