import { useCallback, useEffect, useState } from "react";
import { UserPlus, Trash2 } from "lucide-react";
import { Dialog, Button, Input, Select, Badge, useToast } from "../ui";
import { spaceMembers, addSpaceMember, setSpaceMemberRole, removeSpaceMember, type SpaceMemberInfo } from "../lib/api";

const ROLE_LABEL: Record<string, string> = { owner: "所有者", admin: "管理员", member: "成员", viewer: "只读" };
const ROLE_TONE: Record<string, "brand" | "accent" | "neutral" | "warn"> = { owner: "brand", admin: "accent", member: "neutral", viewer: "warn" };

// SpaceMembers 空间成员管理弹窗：列成员；空间 admin/owner 可邀请/改角色/移除（owner 受保护）。
// 非管理员只读。作用于当前活跃空间（spaceId），个人空间不该打开此弹窗（调用方控制）。
export function SpaceMembers({ open, onClose, spaceId, spaceName, canManage, selfUserId }: {
  open: boolean;
  onClose: () => void;
  spaceId: string;
  spaceName: string;
  canManage: boolean;
  selfUserId: string;
}) {
  const toast = useToast();
  const [rows, setRows] = useState<SpaceMemberInfo[]>([]);
  const [loading, setLoading] = useState(false);
  const [email, setEmail] = useState("");
  const [inviteRole, setInviteRole] = useState("member");
  const [busy, setBusy] = useState(false);

  const refresh = useCallback(async () => {
    if (!spaceId) return;
    setLoading(true);
    try {
      setRows(await spaceMembers(spaceId));
    } catch (e) {
      toast.push("error", (e as Error).message);
    } finally {
      setLoading(false);
    }
  }, [spaceId, toast]);

  useEffect(() => {
    if (open) void refresh();
  }, [open, refresh]);

  const invite = async () => {
    const em = email.trim();
    if (!em) return;
    setBusy(true);
    try {
      await addSpaceMember(spaceId, em, inviteRole);
      setEmail("");
      toast.push("success", `已邀请 ${em}`);
      await refresh();
    } catch (e) {
      toast.push("error", (e as Error).message);
    } finally {
      setBusy(false);
    }
  };

  const changeRole = async (uid: string, role: string) => {
    try {
      await setSpaceMemberRole(spaceId, uid, role);
      await refresh();
    } catch (e) {
      toast.push("error", (e as Error).message);
    }
  };

  const remove = async (m: SpaceMemberInfo) => {
    if (!window.confirm(`把 ${m.name || m.email} 移出「${spaceName}」？`)) return;
    try {
      await removeSpaceMember(spaceId, m.user_id);
      toast.push("success", "已移除");
      await refresh();
    } catch (e) {
      toast.push("error", (e as Error).message);
    }
  };

  return (
    <Dialog open={open} onClose={onClose} title={`成员 · ${spaceName}`}>
      {canManage && (
        <div className="mb-3 flex items-end gap-2">
          <Input
            className="flex-1"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="邀请已注册用户的邮箱"
            onKeyDown={(e) => e.key === "Enter" && invite()}
          />
          <Select className="w-24" value={inviteRole} onChange={(e) => setInviteRole(e.target.value)}>
            <option value="member">成员</option>
            <option value="admin">管理员</option>
            <option value="viewer">只读</option>
          </Select>
          <Button variant="primary" size="sm" icon={UserPlus} onClick={invite} disabled={busy || !email.trim()}>
            邀请
          </Button>
        </div>
      )}
      {!canManage && <p className="mb-2 text-[11px] text-slate-500">你在此空间为只读/成员，仅管理员可增删成员。</p>}

      <ul className="max-h-72 space-y-1 overflow-auto">
        {loading && <li className="px-1 py-2 text-[11px] text-slate-500">加载中…</li>}
        {!loading && rows.length === 0 && <li className="px-1 py-2 text-[11px] text-slate-600">暂无成员</li>}
        {rows.map((m) => {
          const isOwner = m.role === "owner";
          const isSelf = m.user_id === selfUserId;
          return (
            <li key={m.user_id} className="flex items-center gap-2 rounded-md border border-line bg-ink-800/60 px-2.5 py-2">
              <div className="min-w-0 flex-1">
                <div className="truncate text-xs text-slate-200">
                  {m.name || m.email} {isSelf && <span className="text-[10px] text-slate-500">（你）</span>}
                </div>
                <div className="truncate text-[10px] text-slate-500">{m.email}</div>
              </div>
              {canManage && !isOwner ? (
                <Select className="h-8 w-20 text-xs" value={m.role} onChange={(e) => changeRole(m.user_id, e.target.value)}>
                  <option value="member">成员</option>
                  <option value="admin">管理员</option>
                  <option value="viewer">只读</option>
                </Select>
              ) : (
                <Badge tone={ROLE_TONE[m.role] ?? "neutral"}>{ROLE_LABEL[m.role] ?? m.role}</Badge>
              )}
              {canManage && !isOwner && (
                <button onClick={() => remove(m)} className="text-slate-600 transition hover:text-danger" title="移出空间">
                  <Trash2 className="h-3.5 w-3.5" />
                </button>
              )}
            </li>
          );
        })}
      </ul>
    </Dialog>
  );
}
