import type { CSSProperties } from "react";
import { User, ChevronDown, Search as SearchIcon, LogOut, Sun, Moon, Coins, Building2, Users as UsersIcon, Plus, Globe, UserCog } from "lucide-react";
import type { AuthUser, TenantCtx, MyTenant, SpaceCtx, MySpace } from "../lib/api";
import { useHealth } from "../lib/health";
import { isMacDesktop } from "../lib/desktop";
import { useTheme } from "../lib/theme";
import { cn } from "../ui";

// Wails 拖拽区/控件 CSS 变量（浏览器忽略，桌面端生效）。
const DRAG = { "--wails-draggable": "drag" } as CSSProperties;
const NODRAG = { "--wails-draggable": "no-drag" } as CSSProperties;

// 系统状态：把 5 项基建健康收成一个整体状态点（客户不看数据库名，异常时 tooltip 提示项数）。
function SystemStatus({ h }: { h: ReturnType<typeof useHealth> }) {
  const down = [h.gateway, h.db, h.nats, h.milvus, h.neo4j].filter((v) => !v).length;
  const ok = down === 0;
  return (
    <span
      title={ok ? "所有服务运行正常" : `${down} 项服务暂不可用`}
      className={cn(
        "flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-[11px]",
        ok ? "border-line text-slate-500" : "border-warn/40 text-warn",
      )}
    >
      <span className={cn("h-1.5 w-1.5 rounded-full", ok ? "bg-success" : "bg-warn")} />
      {ok ? "系统正常" : "部分异常"}
    </span>
  );
}

// 积分余额芯片：让用户在主产品里随时看到自己租户剩多少积分。点击进「用量」页。
// 硬拦截开启且余额≤0 → 红色「余额不足」；偏低 → 橙；否则常态。
function CreditChip({ tenant, onClick }: { tenant: TenantCtx; onClick?: () => void }) {
  const credits = tenant.credit_balance_micro / 1_000_000;
  const empty = tenant.credit_enforce && credits <= 0;
  const low = !empty && credits > 0 && credits < 10;
  const tone = empty ? "border-danger/50 text-danger" : low ? "border-warn/50 text-warn" : "border-line text-slate-300";
  return (
    <button
      onClick={onClick}
      className={cn("flex items-center gap-1.5 rounded-md border bg-ink-800 px-2.5 py-1 text-xs transition hover:border-ink-600", tone)}
      title={
        `租户 ${tenant.tenant?.name ?? ""} · 积分余额 ${credits.toLocaleString("zh-CN", { maximumFractionDigits: 2 })}` +
        (tenant.credit_enforce ? "（余额≤0 将无法提交任务，请联系管理员充值）" : "（当前不拦截，仅计量）")
      }
    >
      <Coins className="h-3.5 w-3.5 opacity-70" />
      {empty ? "余额不足" : credits.toLocaleString("zh-CN", { maximumFractionDigits: credits < 100 ? 1 : 0 })}
    </button>
  );
}

// 租户切换器：仅当用户属多个租户时显示；切换即改活跃租户（工作区 + 计费上下文）。
function TenantSwitcher({ tenants, activeId, onSwitch }: { tenants: MyTenant[]; activeId?: string; onSwitch?: (id: string) => void }) {
  if (tenants.length < 2) return null;
  return (
    <div className="relative" style={NODRAG}>
      <Building2 className="pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-500" />
      <select
        value={activeId ?? ""}
        onChange={(e) => onSwitch?.(e.target.value)}
        title="切换当前租户（工作区 + 计费）"
        className="appearance-none rounded-md border border-line bg-ink-800 py-1 pl-7 pr-7 text-xs text-slate-300 focus:border-brand focus:outline-none"
      >
        {tenants.map((t) => (
          <option key={t.id} value={t.id}>
            {t.name}
          </option>
        ))}
      </select>
      <ChevronDown className="pointer-events-none absolute right-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-500" />
    </div>
  );
}

// 工作区切换器：切换活跃 Space（共享工作区 — 个人/项目/全员）。含"新建项目空间"。
// 个人空间恒有，故 ≥1 即显示（让用户随时能建/进项目协作空间）。
function SpaceSwitcher({ spaces, activeId, onSwitch, onCreate, onEnableTenantSpace, tenantRole }: { spaces: MySpace[]; activeId?: string; onSwitch?: (id: string) => void; onCreate?: (name: string) => void; onEnableTenantSpace?: () => void; tenantRole?: string }) {
  if (spaces.length === 0) return null;
  const label = (s: MySpace) => (s.kind === "personal" ? "个人空间" : s.name) + (s.kind !== "personal" ? ` · ${s.members}人` : "");
  const canManage = tenantRole === "owner" || tenantRole === "admin";
  const hasTenantSpace = spaces.some((s) => s.kind === "tenant");
  return (
    <div className="flex items-center gap-1" style={NODRAG}>
      <div className="relative">
        <UsersIcon className="pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-500" />
        <select
          value={activeId ?? ""}
          onChange={(e) => onSwitch?.(e.target.value)}
          title="切换当前工作区（共享资源作用域）"
          className="appearance-none rounded-md border border-line bg-ink-800 py-1 pl-7 pr-7 text-xs text-slate-300 focus:border-brand focus:outline-none"
        >
          {spaces.map((s) => (
            <option key={s.id} value={s.id}>
              {label(s)}
            </option>
          ))}
        </select>
        <ChevronDown className="pointer-events-none absolute right-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-500" />
      </div>
      <button
        onClick={() => {
          const name = window.prompt("新建项目空间名称（团队成员可共享此空间的编排/知识库）");
          if (name && name.trim()) onCreate?.(name.trim());
        }}
        title="新建项目空间"
        className="flex items-center rounded-md border border-line bg-ink-800 px-1.5 py-1 text-slate-400 transition hover:border-ink-600 hover:text-slate-200"
      >
        <Plus className="h-3.5 w-3.5" />
      </button>
      {canManage && !hasTenantSpace && (
        <button
          onClick={() => {
            if (window.confirm("启用「全员空间」？将把本租户全部成员纳入一个共享工作区（整租户共享编排/知识库）。")) onEnableTenantSpace?.();
          }}
          title="启用全员空间（整租户共享，自动纳入所有成员）"
          className="flex items-center rounded-md border border-line bg-ink-800 px-1.5 py-1 text-slate-400 transition hover:border-ink-600 hover:text-slate-200"
        >
          <Globe className="h-3.5 w-3.5" />
        </button>
      )}
    </div>
  );
}

// 顶栏：品牌 · 垂直切换 · 健康灯 · 租户/工作区切换 · 积分余额 · 登录用户 + 登出（深色 + 毛玻璃）。
export function TopBar({ user, tenant, tenants = [], onSwitchTenant, space, spaces = [], onSwitchSpace, onCreateSpace, onEnableTenantSpace, onManageMembers, tenantRole, onLogout, onCommand, onOpenUsage }: { user: AuthUser; tenant?: TenantCtx | null; tenants?: MyTenant[]; onSwitchTenant?: (id: string) => void; space?: SpaceCtx | null; spaces?: MySpace[]; onSwitchSpace?: (id: string) => void; onCreateSpace?: (name: string) => void; onEnableTenantSpace?: () => void; onManageMembers?: () => void; tenantRole?: string; onLogout: () => void; onCommand?: () => void; onOpenUsage?: () => void }) {
  const h = useHealth();
  const { theme, toggle } = useTheme();
  return (
    <header
      style={DRAG}
      className={cn("flex h-12 shrink-0 items-center gap-3 border-b border-line bg-ink-900/80 pr-3 backdrop-blur", isMacDesktop() ? "pl-20" : "pl-3")}
    >
      <div className="flex items-center gap-2">
        <div className="flex h-6 w-6 items-center justify-center rounded-md bg-gradient-to-br from-brand to-accent text-xs font-bold text-white">
          S
        </div>
        <span className="brand-gradient text-sm font-semibold">sundynix-agentix</span>
      </div>
      <button
        onClick={onCommand}
        style={NODRAG}
        className="flex items-center gap-2 rounded-md border border-line bg-ink-800 px-2.5 py-1 text-xs text-slate-400 transition hover:border-ink-600 hover:text-slate-200"
        title="命令面板"
      >
        <SearchIcon className="h-3.5 w-3.5" />
        搜索与命令
        <kbd className="rounded border border-line px-1 font-mono text-[10px] text-slate-500">⌘K</kbd>
      </button>
      <div className="ml-2">
        <SystemStatus h={h} />
      </div>
      <div className="ml-auto flex items-center gap-2" style={NODRAG}>
        <TenantSwitcher tenants={tenants} activeId={tenant?.tenant?.id} onSwitch={onSwitchTenant} />
        <SpaceSwitcher spaces={spaces} activeId={space?.space?.id} onSwitch={onSwitchSpace} onCreate={onCreateSpace} onEnableTenantSpace={onEnableTenantSpace} tenantRole={tenantRole} />
        {space?.space && space.space.kind !== "personal" && (
          <button
            onClick={onManageMembers}
            title="管理当前空间成员"
            className="flex items-center rounded-md border border-line bg-ink-800 px-1.5 py-1 text-slate-400 transition hover:border-ink-600 hover:text-slate-200"
          >
            <UserCog className="h-3.5 w-3.5" />
          </button>
        )}
        {tenant?.tenant && <CreditChip tenant={tenant} onClick={onOpenUsage} />}
        <button
          onClick={toggle}
          className="flex items-center rounded-md border border-line bg-ink-800 px-2 py-1 text-slate-400 transition hover:border-ink-600 hover:text-slate-200"
          title={theme === "dark" ? "切换到亮色" : "切换到暗色"}
        >
          {theme === "dark" ? <Sun className="h-3.5 w-3.5" /> : <Moon className="h-3.5 w-3.5" />}
        </button>
        <span className="flex items-center gap-1.5 rounded-md border border-line bg-ink-800 px-2.5 py-1 text-xs text-slate-300" title={user.email}>
          <User className="h-3.5 w-3.5 text-slate-500" />
          {user.name || user.email}
        </span>
        <button
          onClick={onLogout}
          className="flex items-center gap-1 rounded-md border border-line bg-ink-800 px-2 py-1 text-xs text-slate-400 transition hover:border-danger/50 hover:text-danger"
          title="退出登录"
        >
          <LogOut className="h-3.5 w-3.5" />
        </button>
      </div>
    </header>
  );
}
