import { useCallback, useEffect, useState } from "react";
import { Users, UserPlus } from "lucide-react";
import { useTenant } from "../shell/AppShell";
import { listMembers, addMember, setMemberRole, removeMember, ROLE_LABEL, ASSIGNABLE_ROLES, type Member } from "../api";
import { Badge, Button, Input, Panel, Select, Table, Tr, Td, useToast } from "../ui";

// 团队：成员名册 + 邀请 + 改角色 + 移除。写操作按当前角色显隐（owner/admin 可写），
// 真闸在后端（RequireTenantRole ≥admin + owner 保护），这里只是 UX 不误导。
export function Team() {
  const toast = useToast();
  const { ctx, refresh } = useTenant();
  const [members, setMembers] = useState<Member[]>([]);
  const [email, setEmail] = useState("");
  const [role, setRole] = useState<string>("member");
  const [busy, setBusy] = useState(false);

  const canWrite = ctx?.role === "owner" || ctx?.role === "admin";

  const load = useCallback(() => {
    listMembers().then(setMembers).catch(() => {});
  }, []);
  // 切组织后 ctx.tenant.id 变化 → 重拉名册。
  useEffect(load, [load, ctx?.tenant?.id]);

  const invite = async () => {
    if (!email.trim() || busy) return;
    setBusy(true);
    try {
      await addMember(email.trim(), role);
      toast.push("success", "已加入团队");
      setEmail("");
      load();
      refresh(); // 成员数变了
    } catch (e) {
      toast.push("error", (e as Error).message);
    } finally {
      setBusy(false);
    }
  };

  const changeRole = async (m: Member, r: string) => {
    try {
      await setMemberRole(m.user_id, r);
      toast.push("success", `${m.name || m.email} → ${ROLE_LABEL[r] ?? r}`);
      load();
    } catch (e) {
      toast.push("error", (e as Error).message);
      load(); // 失败回滚显示
    }
  };

  const remove = async (m: Member) => {
    if (!window.confirm(`确定把 ${m.name || m.email} 移出团队？`)) return;
    try {
      await removeMember(m.user_id);
      toast.push("success", "已移除");
      load();
      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">{ctx?.tenant?.name ?? "…"} · {members.length} 名成员</p>
      </div>

      {canWrite && (
        <Panel title="邀请成员" icon={UserPlus}>
          <div className="flex flex-wrap items-center gap-2">
            <Input
              className="w-64"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && invite()}
              placeholder="对方注册时用的邮箱"
            />
            <Select value={role} onChange={(e) => setRole(e.target.value)} className="w-28">
              {ASSIGNABLE_ROLES.map((r) => (
                <option key={r} value={r}>{ROLE_LABEL[r]}</option>
              ))}
            </Select>
            <Button variant="primary" icon={UserPlus} onClick={invite} disabled={busy || !email.trim()}>
              邀请
            </Button>
            <span className="text-[11px] text-slate-600">对方需先注册 sundynix 账号，暂不发邀请邮件。</span>
          </div>
        </Panel>
      )}

      <Panel title="成员" icon={Users} bodyClassName="p-0">
        <Table cols={["成员", "角色", "加入时间", canWrite ? "操作" : ""]}>
          {members.map((m) => (
            <Tr key={m.user_id}>
              <Td>
                <div className="text-slate-200">{m.name || "—"}</div>
                <div className="text-[11px] text-slate-500">{m.email}</div>
              </Td>
              <Td>
                {canWrite && m.role !== "owner" ? (
                  <Select value={m.role} onChange={(e) => changeRole(m, e.target.value)} className="h-8 w-24 text-xs">
                    {ASSIGNABLE_ROLES.map((r) => (
                      <option key={r} value={r}>{ROLE_LABEL[r]}</option>
                    ))}
                  </Select>
                ) : (
                  <Badge tone={m.role === "owner" ? "accent" : "neutral"}>{ROLE_LABEL[m.role] ?? m.role}</Badge>
                )}
              </Td>
              <Td>
                <span className="text-xs text-slate-500">{m.joined_at ? new Date(m.joined_at).toLocaleDateString() : "—"}</span>
              </Td>
              <Td>
                {canWrite && m.role !== "owner" && (
                  <Button variant="ghost" onClick={() => remove(m)} className="text-danger">
                    移除
                  </Button>
                )}
              </Td>
            </Tr>
          ))}
        </Table>
        {members.length === 0 && <p className="p-4 text-xs text-slate-600">加载中…</p>}
      </Panel>
    </div>
  );
}
