"use client";

import * as React from "react";
import { cn } from "@/lib/utils";

// ─── Types ────────────────────────────────────────────────────────────────────

export interface NavItem {
  id: string;
  label: string;
  href?: string;
  icon?: React.ReactNode;
  badge?: string | number;
  disabled?: boolean;
}

export interface NavGroup {
  id: string;
  title?: string;
  items: NavItem[];
}

export interface SideNavUser {
  name: string;
  email?: string;
  avatar?: string;
  /** 完成度 0-100 */
  completionPercent?: number;
  completionLabel?: string;
}

export interface SideNavProps extends React.HTMLAttributes<HTMLElement> {
  /** 品牌 Logo/名称区域 */
  logo?: React.ReactNode;
  /** 品牌名 */
  brandName?: string;
  /** 导航分组 */
  groups: NavGroup[];
  /** 当前激活的导航项 id */
  activeId?: string;
  /** 导航项点击回调 */
  onNavClick?: (item: NavItem) => void;
  /** 底部用户信息 */
  user?: SideNavUser;
  /** 底部额外操作区 */
  footerExtra?: React.ReactNode;
  /** 是否折叠（仅展示图标） */
  collapsed?: boolean;
  /** 折叠切换回调 */
  onCollapsedChange?: (collapsed: boolean) => void;
  /** "更多工具"分组标签 */
  moreToolsLabel?: string;
}

// ─── Sub-components ────────────────────────────────────────────────────────────

const NavItemRow = React.memo(
  ({
    item,
    active,
    collapsed,
    onClick,
  }: {
    item: NavItem;
    active: boolean;
    collapsed?: boolean;
    onClick?: () => void;
  }) => {
    return (
      <button
        type="button"
        disabled={item.disabled}
        onClick={onClick}
        title={collapsed ? item.label : undefined}
        className={cn(
          "group relative flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-all duration-200",
          "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-geo-nav-active focus-visible:ring-offset-1 focus-visible:ring-offset-geo-nav",
          "disabled:pointer-events-none disabled:opacity-40",
          active
            ? "bg-geo-nav-active/15 text-geo-nav-active"
            : "text-white/70 hover:bg-white/8 hover:text-white",
          collapsed && "justify-center px-2"
        )}
      >
        {/* active indicator bar */}
        {active && (
          <span className="absolute left-0 top-1/2 h-4 w-0.5 -translate-y-1/2 rounded-full bg-geo-nav-active" />
        )}

        {/* icon */}
        {item.icon && (
          <span
            className={cn(
              "flex h-5 w-5 shrink-0 items-center justify-center transition-colors duration-200",
              active ? "text-geo-nav-active" : "text-white/50 group-hover:text-white/80"
            )}
          >
            {item.icon}
          </span>
        )}

        {/* label */}
        {!collapsed && (
          <span className="flex-1 truncate text-left">{item.label}</span>
        )}

        {/* badge */}
        {!collapsed && item.badge !== undefined && (
          <span
            className={cn(
              "ml-auto flex h-5 min-w-5 items-center justify-center rounded-full px-1.5 text-[10px] font-bold",
              active
                ? "bg-geo-nav-active text-white"
                : "bg-white/15 text-white/80"
            )}
          >
            {item.badge}
          </span>
        )}
      </button>
    );
  }
);
NavItemRow.displayName = "NavItemRow";

// ─── User info footer ──────────────────────────────────────────────────────────

const UserFooter = ({
  user,
  collapsed,
}: {
  user: SideNavUser;
  collapsed?: boolean;
}) => {
  return (
    <div
      className={cn(
        "flex flex-col gap-2 border-t border-white/10 pt-3",
        collapsed && "items-center"
      )}
    >
      {/* Completion progress bar */}
      {!collapsed && user.completionPercent !== undefined && (
        <div className="px-2">
          <div className="mb-1 flex items-center justify-between">
            <span className="text-xs text-white/50">
              {user.completionLabel ?? "Profile Completion"}
            </span>
            <span className="text-xs font-semibold text-white/70">
              {user.completionPercent}%
            </span>
          </div>
          <div className="h-1 w-full overflow-hidden rounded-full bg-white/10">
            <div
              className="h-full rounded-full bg-geo-nav-active transition-all duration-500"
              style={{ width: `${Math.min(100, Math.max(0, user.completionPercent))}%` }}
            />
          </div>
        </div>
      )}

      {/* User row */}
      <div
        className={cn(
          "flex items-center gap-2.5 rounded-lg px-2 py-1.5 transition-colors duration-200 hover:bg-white/8 cursor-pointer",
          collapsed && "justify-center px-2"
        )}
      >
        {/* avatar */}
        <div className="relative shrink-0">
          {user.avatar ? (
            <img
              src={user.avatar}
              alt={user.name}
              className="h-8 w-8 rounded-full object-cover ring-2 ring-white/20"
            />
          ) : (
            <div className="flex h-8 w-8 items-center justify-center rounded-full bg-geo-nav-active/30 text-xs font-bold text-geo-nav-active ring-2 ring-geo-nav-active/30">
              {user.name.slice(0, 2).toUpperCase()}
            </div>
          )}
          <span className="absolute -bottom-px -right-px h-2.5 w-2.5 rounded-full border-2 border-geo-nav bg-primary" />
        </div>

        {/* user info */}
        {!collapsed && (
          <div className="flex-1 min-w-0">
            <p className="text-sm font-semibold text-white truncate">{user.name}</p>
            {user.email && (
              <p className="text-xs text-white/50 truncate">{user.email}</p>
            )}
          </div>
        )}

        {/* chevron */}
        {!collapsed && (
          <svg className="h-3.5 w-3.5 shrink-0 text-white/30" viewBox="0 0 14 14" fill="none">
            <path d="M5 4L8 7L5 10" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        )}
      </div>
    </div>
  );
};

// ─── Main SideNav ──────────────────────────────────────────────────────────────

const SideNav = React.forwardRef<HTMLElement, SideNavProps>(
  (
    {
      className,
      logo,
      brandName = "GEO",
      groups,
      activeId,
      onNavClick,
      user,
      footerExtra,
      collapsed = false,
      onCollapsedChange,
      ...props
    },
    ref
  ) => {
    return (
      <nav
        ref={ref}
        className={cn(
          "flex flex-col h-full bg-geo-nav text-white transition-all duration-300 geo-scrollbar overflow-y-auto",
          collapsed ? "w-16" : "w-60",
          className
        )}
        {...props}
      >
        {/* ── Brand header ── */}
        <div
          className={cn(
            "flex items-center gap-3 px-4 py-4 shrink-0",
            collapsed && "justify-center px-3"
          )}
        >
          {logo && (
            <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-geo-nav-active/20">
              {logo}
            </div>
          )}
          {!collapsed && (
            <span className="text-base font-bold text-white tracking-tight truncate">
              {brandName}
            </span>
          )}
          {/* collapse toggle */}
          {!collapsed && onCollapsedChange && (
            <button
              type="button"
              onClick={() => onCollapsedChange(true)}
              className="ml-auto flex h-6 w-6 items-center justify-center rounded-md text-white/40 hover:bg-white/10 hover:text-white transition-colors duration-200"
              title="折叠导航"
            >
              <svg viewBox="0 0 16 16" className="h-3.5 w-3.5" fill="none">
                <path d="M10 4L6 8L10 12" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
          )}
          {collapsed && onCollapsedChange && (
            <button
              type="button"
              onClick={() => onCollapsedChange(false)}
              className="flex h-6 w-6 items-center justify-center rounded-md text-white/40 hover:bg-white/10 hover:text-white transition-colors duration-200"
              title="展开导航"
            >
              <svg viewBox="0 0 16 16" className="h-3.5 w-3.5" fill="none">
                <path d="M6 4L10 8L6 12" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </button>
          )}
        </div>

        {/* ── Nav groups ── */}
        <div className="flex-1 overflow-y-auto px-3 pb-3 geo-scrollbar space-y-5">
          {groups.map((group, gIdx) => (
            <div key={group.id}>
              {group.title && !collapsed && (
                <p className="mb-1.5 px-3 text-[10px] font-semibold uppercase tracking-widest text-white/30">
                  {group.title}
                </p>
              )}
              {gIdx > 0 && !group.title && collapsed && (
                <div className="my-2 h-px bg-white/10" />
              )}
              <div className="space-y-0.5">
                {group.items.map((item) => (
                  <NavItemRow
                    key={item.id}
                    item={item}
                    active={item.id === activeId}
                    collapsed={collapsed}
                    onClick={() => onNavClick?.(item)}
                  />
                ))}
              </div>
            </div>
          ))}
        </div>

        {/* ── Footer ── */}
        <div className="px-3 pb-4 shrink-0 space-y-2">
          {footerExtra && (
            <div className={cn("text-white/70", collapsed && "flex justify-center")}>
              {footerExtra}
            </div>
          )}
          {user && <UserFooter user={user} collapsed={collapsed} />}
        </div>
      </nav>
    );
  }
);
SideNav.displayName = "SideNav";

export { SideNav };
