// Admin users management

const AdminsPage = () => {
  const [editingAdmin, setEditingAdmin] = useState(null);
  const [permConfirm, setPermConfirm] = useState(null);
  const [addOpen, setAddOpen] = useState(false);
  const toast = useToast();

  return (
    <div className="fade-in">
      <PageHeader
        title="管理員"
        subtitle={`${MOCK.ADMINS.length} 位管理員 · ${MOCK.ADMINS.filter(a=>a.status==="active").length} 位活躍`}
        actions={<Button variant="primary" icon="plus" onClick={() => setAddOpen(true)}>新增管理員</Button>}
      />

      {/* Role legend */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12, marginBottom: 24 }}>
        {Object.entries(MOCK.ROLES).map(([key, r]) => {
          const count = MOCK.ADMINS.filter(a => a.role === key).length;
          return (
            <Card key={key} padding={16}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
                <Badge tone={r.color} size="sm">{r.label}</Badge>
                <span className="mono" style={{ fontSize: 13, color: "var(--ink-3)" }}>{count} 人</span>
              </div>
              <div style={{ fontSize: 12, color: "var(--ink-2)", lineHeight: 1.5 }}>{r.desc}</div>
            </Card>
          );
        })}
      </div>

      <Table
        columns={[
          { title: "管理員", render: a => (
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <Avatar hue={((a.name.charCodeAt(0) || 0) * 7) % 360} glyph={a.name[0]} size={32}/>
              <div>
                <div style={{ fontSize: 13.5, fontWeight: 500 }}>{a.name} {a.email === localStorage.getItem("adminEmail") && <span style={{ fontSize: 11, color: "var(--ink-3)" }}>(你)</span>}</div>
                <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{a.email}</div>
              </div>
            </div>
          ) },
          { title: "角色", render: a => <Badge tone={MOCK.ROLES[a.role].color}>{MOCK.ROLES[a.role].label}</Badge> },
          { title: "MFA", render: a => a.mfa ? <Badge tone="success" size="sm" dot>已啟用</Badge> : <Badge tone="warn" size="sm" dot>未啟用</Badge> },
          { title: "狀態", render: a => a.status === "active" ? <Badge tone="success" size="sm" dot>使用中</Badge> : <Badge tone="default" size="sm">已停用</Badge> },
          { title: "上次登入", render: a => <span style={{ fontSize: 12.5, color: "var(--ink-3)" }}>{a.lastLogin}</span> },
          { title: "建立於", render: a => <span className="mono" style={{ fontSize: 12, color: "var(--ink-3)" }}>{a.createdAt}</span> },
          { title: "", width: 80, render: a => (
            <div style={{ display: "flex", gap: 4 }}>
              <Button variant="ghost" size="sm" icon="edit" onClick={() => setEditingAdmin(a)}/>
              {a.id !== "A001" && <Button variant="ghost" size="sm" icon="more"/>}
            </div>
          ) },
        ]}
        rows={MOCK.ADMINS}
      />

      {/* Edit admin modal */}
      <Modal open={!!editingAdmin} onClose={() => setEditingAdmin(null)} width={520}>
        {editingAdmin && <EditAdminForm admin={editingAdmin} onClose={() => setEditingAdmin(null)} onSubmit={(newRole) => {
          setPermConfirm({ admin: editingAdmin, newRole });
          setEditingAdmin(null);
        }}/>}
      </Modal>

      {/* Add admin modal */}
      <Modal open={addOpen} onClose={() => setAddOpen(false)} width={520}>
        <AddAdminForm onClose={() => setAddOpen(false)} onSubmit={() => {
          setAddOpen(false);
          toast({ title: "邀請已發送", message: "新管理員將收到 Email 設定密碼與 MFA" });
        }}/>
      </Modal>

      <ConfirmDialog
        open={!!permConfirm}
        onClose={() => setPermConfirm(null)}
        onConfirm={() => {
          toast({ title: "權限已更新", message: `${permConfirm.admin.name} → ${MOCK.ROLES[permConfirm.newRole]?.label}` });
          setPermConfirm(null);
        }}
        title={`修改管理員權限`}
        description={<>將 <b>{permConfirm?.admin?.name}</b> 的角色從 <Badge tone={MOCK.ROLES[permConfirm?.admin?.role]?.color} size="sm">{MOCK.ROLES[permConfirm?.admin?.role]?.label}</Badge> 變更為 <Badge tone={MOCK.ROLES[permConfirm?.newRole]?.color} size="sm">{MOCK.ROLES[permConfirm?.newRole]?.label}</Badge>。此變更立即生效,對方需重新登入。</>}
        requireOtp
        variant="danger"
        icon="key"
        confirmText="確認修改"
      />
    </div>
  );
};

const EditAdminForm = ({ admin, onClose, onSubmit }) => {
  const [role, setRole] = useState(admin.role);
  const changed = role !== admin.role;
  return (
    <div style={{ padding: 24 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 20 }}>
        <Avatar hue={((admin.name.charCodeAt(0) || 0) * 7) % 360} glyph={admin.name[0]} size={44}/>
        <div>
          <div style={{ fontSize: 16, fontWeight: 600 }}>編輯 {admin.name}</div>
          <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{admin.email}</div>
        </div>
      </div>

      <div style={{ marginBottom: 14 }}>
        <label style={labelStyle}>角色</label>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {Object.entries(MOCK.ROLES).map(([key, r]) => (
            <button key={key} onClick={() => setRole(key)} style={{
              display: "flex", alignItems: "flex-start", gap: 12, padding: "12px 14px",
              borderRadius: 10, textAlign: "left", width: "100%",
              border: "1.5px solid " + (role === key ? "var(--ink)" : "var(--border)"),
              background: role === key ? "var(--surface-2)" : "var(--surface)",
            }}>
              <div style={{
                width: 16, height: 16, borderRadius: 999, border: "1.5px solid " + (role === key ? "var(--ink)" : "var(--border-strong)"),
                display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, marginTop: 2,
              }}>
                {role === key && <div style={{ width: 8, height: 8, background: "var(--ink)", borderRadius: 999 }}/>}
              </div>
              <div style={{ flex: 1 }}>
                <Badge tone={r.color} size="sm">{r.label}</Badge>
                <div style={{ fontSize: 12, color: "var(--ink-2)", marginTop: 4 }}>{r.desc}</div>
              </div>
            </button>
          ))}
        </div>
      </div>

      <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 20 }}>
        <Button variant="secondary" onClick={onClose}>取消</Button>
        <Button variant="primary" disabled={!changed} onClick={() => onSubmit(role)}>更新權限</Button>
      </div>
    </div>
  );
};

const AddAdminForm = ({ onClose, onSubmit }) => {
  const [email, setEmail] = useState("");
  const [name, setName] = useState("");
  const [role, setRole] = useState("ops_admin");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const toast = useToast();

  async function handleSend() {
    setError("");
    setLoading(true);
    try {
      const res = await fetch("/api/admin/invite", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, name }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setError(data.error || "發送失敗，請稍後再試");
        return;
      }
      onSubmit();
    } catch (e) {
      setError("網路錯誤，請稍後再試");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div style={{ padding: 24 }}>
      <div style={{ fontSize: 18, fontWeight: 600, marginBottom: 4 }}>新增管理員</div>
      <div style={{ fontSize: 13, color: "var(--ink-3)", marginBottom: 20 }}>對方將收到 Email 邀請，內含臨時密碼，首次登入後請立即修改密碼</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <div><label style={labelStyle}>姓名</label><Input value={name} onChange={e=>setName(e.target.value)} placeholder="王小明"/></div>
        <div><label style={labelStyle}>Email</label><Input icon="mail" value={email} onChange={e=>setEmail(e.target.value)} placeholder="name@example.com"/></div>
        <div>
          <label style={labelStyle}>角色</label>
          <Select value={role} onChange={setRole} options={Object.entries(MOCK.ROLES).map(([k,r]) => ({ value: k, label: r.label }))} style={{ width: "100%" }}/>
          <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 6 }}>{MOCK.ROLES[role].desc}</div>
        </div>
        {error && (
          <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12.5, color: "var(--danger)", padding: "8px 12px", background: "var(--danger-soft)", borderRadius: 8 }}>
            <Icon name="alert" size={14}/>{error}
          </div>
        )}
      </div>
      <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", marginTop: 20 }}>
        <Button variant="secondary" onClick={onClose} disabled={loading}>取消</Button>
        <Button variant="primary" disabled={!email || !name || loading} onClick={handleSend}>
          {loading ? "發送中…" : "發送邀請"}
        </Button>
      </div>
    </div>
  );
};

window.AdminsPage = AdminsPage;
