"use client"
import {
  Activity,
  BarChart3,
  ChevronsLeft,
  ChevronsRight,
  ClipboardList,
  Code,
  ComputerIcon,
  DollarSign,
  Home,
  KeyRound,
  type LucideIcon,
  Package,
  Shield,
  Users,
} from "lucide-react"
import Link from "next/link"
import { usePathname } from "next/navigation"
import { createContext, type ReactNode, useContext, useState } from "react"
import { twJoin } from "tailwind-merge"
import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Separator } from "@/components/ui/separator"
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip"

// Navigation Context
interface NavigationContextType {
  collapsed: boolean
  pathname: string
  isActive: (path: string) => boolean
}

const NavigationContext = createContext<NavigationContextType | undefined>(
  undefined,
)

const useNavigation = () => {
  const context = useContext(NavigationContext)
  if (!context) {
    throw new Error("Navigation components must be used within Navigation")
  }
  return context
}

// NavGroup Component
interface NavGroupProps {
  title: string
  children: ReactNode
}

function NavGroup({ title, children }: NavGroupProps) {
  const { collapsed } = useNavigation()

  return (
    <div className="px-3">
      {!collapsed && (
        <h3 className="px-3 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
          {title}
        </h3>
      )}
      <ul className={`${collapsed ? "mt-0" : "mt-2"} space-y-1`}>{children}</ul>
    </div>
  )
}

// NavItem Component
interface NavItemProps {
  href: string
  icon: LucideIcon
  label: string
}

function NavItem({ href, icon: Icon, label }: NavItemProps) {
  const { collapsed, isActive } = useNavigation()
  const active = isActive(href)

  const linkContent = (
    <Link
      href={href}
      className={`flex items-center ${
        collapsed ? "justify-center w-10 h-10" : "px-3 py-2"
      } rounded-md transition-colors ${
        active
          ? "bg-accent text-accent-foreground"
          : "text-muted-foreground hover:bg-accent hover:text-accent-foreground"
      }`}
    >
      <Icon className={`h-5 w-5 ${collapsed ? "" : "shrink-0"}`} />
      {!collapsed && <span className="ml-3 font-medium text-sm">{label}</span>}
    </Link>
  )

  if (collapsed) {
    return (
      <li>
        <Tooltip>
          <TooltipTrigger asChild>{linkContent}</TooltipTrigger>
          <TooltipContent side="right">
            <p>{label}</p>
          </TooltipContent>
        </Tooltip>
      </li>
    )
  }

  return <li>{linkContent}</li>
}

// NavSeparator Component
function NavSeparator() {
  const { collapsed } = useNavigation()

  if (collapsed) return null

  return (
    <div className="my-4">
      <Separator />
    </div>
  )
}

// Main Navigation Component
export default function Navigation() {
  const [collapsed, setCollapsed] = useState(false)
  const pathname = usePathname()

  const isActive = (path: string) => {
    return path === "/" ? pathname === path : pathname.startsWith(path)
  }

  const contextValue: NavigationContextType = {
    collapsed,
    pathname,
    isActive,
  }

  return (
    <TooltipProvider delayDuration={0}>
      <NavigationContext.Provider value={contextValue}>
        <aside
          className={twJoin(
            "bg-background border-r border-border transition-all duration-300 ease-in-out flex flex-col",
            collapsed ? "w-16" : "w-64",
          )}
        >
          {/* Logo */}
          <div className="h-16 flex items-center justify-center border-b border-border">
            {!collapsed ? (
              <span className="text-xl font-bold tracking-wide text-foreground">
                管理系统
              </span>
            ) : (
              <span className="text-xl font-bold mx-auto text-foreground">
                <ComputerIcon />
              </span>
            )}
          </div>

          {/* Navigation Menu */}
          <ScrollArea className="flex-1 py-3">
            <nav className="space-y-3">
              {/* 概览 */}
              <NavGroup title="概览">
                <NavItem href="/" icon={Home} label="首页" />
                <NavItem href="/statistics" icon={BarChart3} label="数据统计" />
              </NavGroup>

              {/*<NavSeparator />*/}

              {/* IP 资源 */}
              {/*<NavGroup title="IP 资源">
                <NavItem href="/proxy/nodes" icon={Globe} label="节点列表" />
                <NavItem href="/proxy/pools" icon={Server} label="IP池管理" />
              </NavGroup>*/}

              <NavSeparator />

              {/* 客户 */}
              <NavGroup title="客户">
                <NavItem href="/user" icon={Users} label="客户管理" />
                <NavItem href="/trade" icon={Activity} label="交易明细" />
                <NavItem href="/billing" icon={DollarSign} label="账单详情" />
              </NavGroup>

              <NavSeparator />

              {/* 运营 */}
              <NavGroup title="运营">
                <NavItem href="/resources" icon={Package} label="套餐管理" />
                <NavItem href="/batch" icon={ClipboardList} label="使用记录" />
                <NavItem href="/channel" icon={Code} label="IP管理" />
              </NavGroup>

              <NavSeparator />

              {/* 系统 */}
              <NavGroup title="系统">
                {/*<NavItem href="/settings" icon={Settings} label="系统设置" />*/}
                <NavItem href="/admin" icon={Shield} label="管理员" />
                <NavItem href="/roles" icon={KeyRound} label="角色列表" />
                <NavItem href="/permissions" icon={Shield} label="权限列表" />
                {/*<NavItem href="/logs" icon={FileText} label="系统日志" />*/}
              </NavGroup>
            </nav>
          </ScrollArea>

          {/* Toggle Button */}
          <div className="p-4 border-t border-border mt-auto">
            <Button
              variant="ghost"
              onClick={() => setCollapsed(!collapsed)}
              className="w-full justify-center text-muted-foreground hover:bg-accent hover:text-accent-foreground"
            >
              {collapsed ? (
                <ChevronsRight className="h-5 w-5" />
              ) : (
                <>
                  <ChevronsLeft className="h-5 w-5" />
                  <span className="ml-2 text-sm">收起菜单</span>
                </>
              )}
            </Button>
          </div>
        </aside>
      </NavigationContext.Provider>
    </TooltipProvider>
  )
}
