// user-management-screen.jsx — Admin-only user list with create/edit/activate/deactivate/delete
// Displays: name, email, role, status, limits usage, expiry, actions
const { useState, useCallback } = React;

// ─── Create user modal ────────────────────────────────────────────────────
const CreateUserModal = ({ open, onClose, onCreated }) => {
  const [form, setForm] = useState({ email: "", password: "", name: "", role: "user", status: "pending" });
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const toast = useToast();

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!form.email || !form.password || !form.name) { setError("Email, password, name required"); return; }
    setSaving(true); setError("");
    try {
      await UserApi.create(form);
      toast.success("User created");
      onCreated();
      onClose();
      setForm({ email: "", password: "", name: "", role: "user", status: "pending" });
    } catch (err) {
      setError(err.message);
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal open={open} onClose={onClose} title="Create User" width={440}
      footer={
        <>
          <button className="btn ghost" onClick={onClose}>Cancel</button>
          <button className="btn primary" onClick={handleSubmit} disabled={saving}>{saving ? "Creating…" : "Create"}</button>
        </>
      }
    >
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        {error && <div style={{ color: "var(--red)", fontSize: 13 }}>{error}</div>}
        {[
          { label: "Name", key: "name", type: "text", placeholder: "Full name" },
          { label: "Email", key: "email", type: "email", placeholder: "user@example.com" },
          { label: "Password", key: "password", type: "password", placeholder: "Password" },
        ].map(({ label, key, type, placeholder }) => (
          <div key={key}>
            <label style={{ display: "block", fontSize: 12, fontWeight: 500, marginBottom: 5, color: "var(--fg-2)" }}>{label}</label>
            <input className="input" type={type} placeholder={placeholder} value={form[key]}
              onChange={e => set(key, e.target.value)} style={{ width: "100%", boxSizing: "border-box" }} />
          </div>
        ))}
        <div>
          <label style={{ display: "block", fontSize: 12, fontWeight: 500, marginBottom: 5, color: "var(--fg-2)" }}>Role</label>
          <select className="input" value={form.role} onChange={e => set("role", e.target.value)} style={{ width: "100%", boxSizing: "border-box" }}>
            <option value="user">User</option>
            <option value="admin">Admin</option>
          </select>
        </div>
        <div>
          <label style={{ display: "block", fontSize: 12, fontWeight: 500, marginBottom: 5, color: "var(--fg-2)" }}>Initial Status</label>
          <select className="input" value={form.status} onChange={e => set("status", e.target.value)} style={{ width: "100%", boxSizing: "border-box" }}>
            <option value="pending">Pending (requires activation)</option>
            <option value="active">Active</option>
          </select>
        </div>
      </div>
    </Modal>
  );
};

// ─── Edit limits modal ────────────────────────────────────────────────────
const EditLimitsModal = ({ open, onClose, user, onSaved }) => {
  const [maxBots, setMaxBots] = useState(user?.limits?.maxBots ?? 3);
  const [maxBotConfigs, setMaxBotConfigs] = useState(user?.limits?.maxBotConfigs ?? 5);
  const [renewDays, setRenewDays] = useState("");
  const [saving, setSaving] = useState(false);
  const toast = useToast();

  const handleSave = async () => {
    setSaving(true);
    try {
      const body = { limits: { maxBots: Number(maxBots), maxBotConfigs: Number(maxBotConfigs) } };
      if (renewDays) body.renewDays = Number(renewDays);
      await UserApi.update(user._id, body);
      toast.success("Limits updated");
      onSaved();
      onClose();
    } catch (err) {
      toast.error(err.message);
    } finally {
      setSaving(false);
    }
  };

  if (!user) return null;
  const expiry = user.limits?.expiresAt ? new Date(user.limits.expiresAt) : null;
  const daysLeft = expiry ? Math.ceil((expiry - Date.now()) / 86400000) : null;

  return (
    <Modal open={open} onClose={onClose} title={`Limits: ${user.name}`} width={400}
      footer={
        <>
          <button className="btn ghost" onClick={onClose}>Cancel</button>
          <button className="btn primary" onClick={handleSave} disabled={saving}>{saving ? "Saving…" : "Save"}</button>
        </>
      }
    >
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <div style={{ fontSize: 12, color: "var(--fg-3)" }}>
          Expiry: {expiry ? expiry.toLocaleDateString() : "Never"} {daysLeft !== null ? `(${daysLeft}d remaining)` : ""}
        </div>
        {[
          { label: "Max Bots (0 = unlimited)", key: "maxBots", val: maxBots, set: setMaxBots },
          { label: "Max Configs (0 = unlimited)", key: "maxBotConfigs", val: maxBotConfigs, set: setMaxBotConfigs },
        ].map(({ label, key, val, set }) => (
          <div key={key}>
            <label style={{ display: "block", fontSize: 12, fontWeight: 500, marginBottom: 5, color: "var(--fg-2)" }}>{label}</label>
            <input className="input" type="number" min="0" value={val}
              onChange={e => set(e.target.value)} style={{ width: "100%", boxSizing: "border-box" }} />
          </div>
        ))}
        <div>
          <label style={{ display: "block", fontSize: 12, fontWeight: 500, marginBottom: 5, color: "var(--fg-2)" }}>
            Renew (extend expiry by N days from now, leave empty to skip)
          </label>
          <input className="input" type="number" min="1" placeholder="e.g. 30" value={renewDays}
            onChange={e => setRenewDays(e.target.value)} style={{ width: "100%", boxSizing: "border-box" }} />
        </div>
      </div>
    </Modal>
  );
};

// ─── Main user management screen ─────────────────────────────────────────
const UserManagementScreen = ({ currentUser }) => {
  const { data: users, loading, refetch } = useApi(UserApi.list, []);
  const [showCreate, setShowCreate] = useState(false);
  const [editLimitsUser, setEditLimitsUser] = useState(null);
  const [expandedUserId, setExpandedUserId] = useState(null);
  const toast = useToast();
  const confirm = useConfirm();

  const handleToggleStatus = async (user) => {
    const newStatus = user.status === "active" ? "disabled" : "active";
    const label = newStatus === "active" ? "activate" : "deactivate";
    const ok = await confirm(`${label.charAt(0).toUpperCase() + label.slice(1)} user?`, `${label} ${user.name}`);
    if (!ok) return;
    try {
      await UserApi.update(user._id, { status: newStatus });
      toast.success(`User ${label}d`);
      refetch();
    } catch (err) {
      toast.error(err.message);
    }
  };

  const handleDelete = async (user) => {
    const ok = await confirm("Delete user?", `This will permanently delete ${user.name}. This cannot be undone.`);
    if (!ok) return;
    try {
      await UserApi.delete(user._id);
      toast.success("User deleted");
      refetch();
    } catch (err) {
      toast.error(err.message);
    }
  };

  const formatExpiry = (user) => {
    const exp = user.limits?.expiresAt;
    if (!exp) return <span className="muted">Never</span>;
    const d = new Date(exp);
    const days = Math.ceil((d - Date.now()) / 86400000);
    const color = days < 0 ? "var(--red)" : days < 7 ? "var(--yellow)" : "var(--fg-2)";
    return <span style={{ fontSize: 12, color }}>{days < 0 ? "Expired" : `${days}d`}</span>;
  };

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1 className="page-title">Users</h1>
          <div className="page-sub">Manage user accounts and access.</div>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button className="btn" onClick={refetch}><I.Refresh /> Refresh</button>
          <button className="btn primary" onClick={() => setShowCreate(true)}><I.Plus /> New User</button>
        </div>
      </div>

      <Card flush>
        <table className="table">
          <thead>
            <tr>
              <th>Name</th>
              <th>Email</th>
              <th>Role</th>
              <th>Status</th>
              <th>Bots</th>
              <th>Configs</th>
              <th>Expires</th>
              <th style={{ width: 160 }}>Actions</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <SkeletonRows cols={8} rows={3} />
            ) : (users || []).length === 0 ? (
              <tr><td colSpan={8}><Empty icon={I.Users} title="No users" sub="Create the first user." /></td></tr>
            ) : (
              (users || []).map(u => (
                <React.Fragment key={u._id}>
                <tr>
                  <td style={{ fontWeight: 500 }}>{u.name}</td>
                  <td className="mono" style={{ fontSize: 12 }}>{u.email}</td>
                  <td>
                    <span style={{ fontSize: 11, padding: "2px 7px", borderRadius: 4, background: u.role === "admin" ? "var(--accent-bg, rgba(99,102,241,0.15))" : "var(--surface-2)", color: u.role === "admin" ? "var(--accent)" : "var(--fg-3)" }}>
                      {u.role}
                    </span>
                  </td>
                  <td><StatusBadge status={u.status} /></td>
                  <td style={{ fontSize: 12 }}>
                    {u.role === "admin" ? "∞" : `—/${u.limits?.maxBots === 0 ? "∞" : u.limits?.maxBots ?? 3}`}
                  </td>
                  <td style={{ fontSize: 12 }}>
                    {u.role === "admin" ? "∞" : `—/${u.limits?.maxBotConfigs === 0 ? "∞" : u.limits?.maxBotConfigs ?? 5}`}
                  </td>
                  <td>{u.role === "admin" ? <span className="muted">N/A</span> : formatExpiry(u)}</td>
                  <td>
                    <div style={{ display: "flex", gap: 4 }}>
                      <button
                        className="btn ghost sm"
                        onClick={() => setExpandedUserId(prev => prev === u._id ? null : u._id)}
                        title="Resources"
                        style={{ fontSize: 11, minWidth: 24 }}
                      >
                        {expandedUserId === u._id ? "\u25BC" : "\u25B6"}
                      </button>
                      <button
                        className="btn ghost sm"
                        onClick={() => handleToggleStatus(u)}
                        disabled={u._id === currentUser?.id}
                        title={u.status === "active" ? "Deactivate" : "Activate"}
                      >
                        {u.status === "active" ? "Disable" : "Activate"}
                      </button>
                      <button
                        className="btn ghost sm"
                        onClick={() => setEditLimitsUser(u)}
                        title="Edit limits"
                      >
                        Limits
                      </button>
                      <button
                        className="btn ghost sm danger"
                        onClick={() => handleDelete(u)}
                        disabled={u._id === currentUser?.id}
                        title="Delete user"
                      >
                        Del
                      </button>
                    </div>
                  </td>
                </tr>
                {expandedUserId === u._id && (
                  <tr><td colSpan={8} style={{ padding: "0 8px 8px" }}>
                    <UserResourcePanel userId={u._id} onChanged={refetch} />
                  </td></tr>
                )}
                </React.Fragment>
              ))
            )}
          </tbody>
        </table>
      </Card>

      <CreateUserModal open={showCreate} onClose={() => setShowCreate(false)} onCreated={refetch} />
      <EditLimitsModal open={!!editLimitsUser} onClose={() => setEditLimitsUser(null)} user={editLimitsUser} onSaved={refetch} />
    </div>
  );
};

Object.assign(window, { UserManagementScreen });
