import { useState } from "react";
import { Building2, Plus, Check } from "lucide-react";
import { useTenant } from "../shell/AppShell";
import { createTenant, switchTenant, fmtCredits } from "../api";
import { Badge, Button, Input, Panel, useToast } from "../ui";

// 组织：我所属的组织列表（余额/成员数）+ 自助新建（创建者即 owner，建完后端自动切入）+ 切换。
export function Orgs() {
  const toast = useToast();
  const { tenants, active, refresh } = useTenant();
  const [name, setName] = useState("");
  const [busy, setBusy] = useState(false);

  const create = async () => {
    if (!name.trim() || busy) return;
    setBusy(true);
    try {
      await createTenant(name.trim());
      toast.push("success", "组织已创建，你是所有者");
      setName("");
      refresh();
    } catch (e) {
      toast.push("error", (e as Error).message);
    } finally {
      setBusy(false);
    }
  };

  const activate = async (id: string) => {
    if (id === active) return;
    try {
      await switchTenant(id);
      refresh();
    } catch (e) {
      toast.push("error", (e as Error).message);
    }
  };

  return (
    <div className="mx-auto max-w-3xl space-y-4 p-8">
      <div>
        <h1 className="text-xl font-semibold tracking-tight text-slate-100">组织</h1>
        <p className="mt-1 text-xs text-slate-500">你所属的 {tenants.length} 个组织；切换后团队/账单页随之切换。</p>
      </div>

      <Panel title="新建组织" icon={Plus}>
        <div className="flex flex-wrap items-center gap-2">
          <Input
            className="w-64"
            value={name}
            onChange={(e) => setName(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && create()}
            placeholder="组织名称，如：某某科技"
          />
          <Button variant="primary" icon={Plus} onClick={create} disabled={busy || !name.trim()}>
            创建
          </Button>
          <span className="text-[11px] text-slate-600">创建者自动成为所有者。</span>
        </div>
      </Panel>

      <Panel title="我的组织" icon={Building2} bodyClassName="p-2">
        <div className="space-y-1">
          {tenants.map((t) => (
            <button key={t.id} onClick={() => activate(t.id)}
              className="flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-left transition-colors hover:bg-ink-850">
              <div className="min-w-0 flex-1">
                <div className="flex items-center gap-2">
                  <span className="truncate text-sm text-slate-200">{t.name}</span>
                  {t.id === active && (
                    <Badge tone="accent">
                      <Check className="mr-0.5 inline h-3 w-3" />当前
                    </Badge>
                  )}
                  {t.shared_billing && <Badge tone="neutral">共享计费</Badge>}
                </div>
                <div className="mt-0.5 text-[11px] text-slate-500">
                  {t.members} 名成员 · 套餐 {t.plan}
                </div>
              </div>
              <span className="text-xs tabular-nums text-slate-400">{fmtCredits(t.credit_balance_micro)} 积分</span>
            </button>
          ))}
          {tenants.length === 0 && <p className="p-2 text-xs text-slate-600">加载中…</p>}
        </div>
      </Panel>
    </div>
  );
}
