// Users management screen — admin / hr_manager only.

const { Avatar: GUsersAvatar } = window.UI;

const ROLE_OPTIONS = [
  { value: "admin",      label: "Admin",       desc: "Full system access" },
  { value: "hr_manager", label: "HR Manager",  desc: "Manage team + content" },
  { value: "recruiter",  label: "Recruiter",   desc: "Edit positions & candidates" },
  { value: "viewer",     label: "Viewer",      desc: "Read-only access" },
];
const ROLE_BY_VALUE = Object.fromEntries(ROLE_OPTIONS.map((r) => [r.value, r]));

const fmt = (d) => {
  if (!d) return "—";
  try { return new Date(d).toLocaleString("en-GB", { year: "numeric", month: "short", day: "2-digit", hour: "2-digit", minute: "2-digit" }); }
  catch { return d; }
};

window.UsersScreen = function UsersScreen({ auth }) {
  const [users, setUsers] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState("");
  const [busy, setBusy] = React.useState({});  // { [userId]: "deleting" | "saving" }
  const [confirmDelete, setConfirmDelete] = React.useState(null); // user obj
  const [toast, setToast] = React.useState("");

  const refresh = async () => {
    setLoading(true); setError("");
    const { data, error } = await auth.listUsers();
    if (error) { setError(error.message); setLoading(false); return; }
    setUsers(data || []);
    setLoading(false);
  };

  React.useEffect(() => { refresh(); }, []);

  const showToast = (msg) => {
    setToast(msg);
    setTimeout(() => setToast(""), 2400);
  };

  const handleRoleChange = async (u, newRole) => {
    if (newRole === u.role) return;
    setBusy((b) => ({ ...b, [u.id]: "saving" }));
    const { error } = await auth.setUserRole(u.id, newRole);
    setBusy((b) => { const { [u.id]: _, ...rest } = b; return rest; });
    if (error) { showToast("❌ " + error.message); return; }
    showToast("✓ ตั้ง role " + (ROLE_BY_VALUE[newRole]?.label || newRole) + " แล้ว");
    refresh();
  };

  const handleDelete = async (u) => {
    setBusy((b) => ({ ...b, [u.id]: "deleting" }));
    const { error } = await auth.deleteUser(u.id);
    setBusy((b) => { const { [u.id]: _, ...rest } = b; return rest; });
    setConfirmDelete(null);
    if (error) { showToast("❌ " + error.message); return; }
    showToast("✓ ลบ " + u.email + " แล้ว");
    refresh();
  };

  const me = auth.user;
  const myRole = auth.role;
  const iAmAdmin = myRole === "admin";

  // Can the current user change/delete a target user?
  const canActOn = (u) => {
    if (u.id === me?.id) return false;          // never act on yourself here
    if (u.role === "admin" && !iAmAdmin) return false; // only admin can touch admins
    return true;
  };
  // Which role values can I assign to user u?
  const allowedRolesFor = (u) => {
    const opts = ROLE_OPTIONS.filter((r) => {
      if (r.value === "admin" && !iAmAdmin) return false;
      return true;
    });
    return opts;
  };

  return (
    <div className="fade-in">
      <div className="page-head">
        <div>
          <div className="page-eyebrow">User management</div>
          <h1 className="page-title">Team & access</h1>
          <div className="page-sub">
            จัดการ role ของสมาชิกในทีม{iAmAdmin ? "" : " (HR Manager ไม่สามารถเปลี่ยน role ของ Admin ได้)"}
          </div>
        </div>
        <button className="btn btn-ghost" onClick={refresh} disabled={loading}>
          <Icon name="refresh-cw" size={14}/>{loading ? "โหลด…" : "Refresh"}
        </button>
      </div>

      {error && (
        <div className="banner banner-info" style={{ marginBottom: 14, background: "#FEE2E2", borderColor: "#FCA5A5", color: "#991B1B" }}>
          <Icon name="alert" size={14} className="banner-icon"/>
          <div className="banner-body" style={{ fontSize: 13 }}>{error}</div>
        </div>
      )}

      {toast && (
        <div className="banner banner-info" style={{ marginBottom: 14 }}>
          <Icon name="info" size={14} className="banner-icon"/>
          <div className="banner-body" style={{ fontSize: 13 }}>{toast}</div>
        </div>
      )}

      <div className="card">
        <table className="tbl">
          <thead>
            <tr>
              <th>User</th>
              <th>Role</th>
              <th>Last sign in</th>
              <th>Joined</th>
              <th>Email</th>
              <th style={{ textAlign: "right" }}></th>
            </tr>
          </thead>
          <tbody>
            {loading && (
              <tr><td colSpan="6" className="muted" style={{ padding: 18 }}>กำลังโหลด…</td></tr>
            )}
            {!loading && users.length === 0 && (
              <tr><td colSpan="6" className="muted" style={{ padding: 18 }}>ยังไม่มี user</td></tr>
            )}
            {users.map((u) => {
              const isMe = u.id === me?.id;
              const allowed = allowedRolesFor(u);
              const lockReason = !canActOn(u)
                ? (isMe ? "(คุณเอง)" : (u.role === "admin" ? "(admin)" : ""))
                : "";
              return (
                <tr key={u.id}>
                  <td>
                    <div className="row gap-10">
                      <GUsersAvatar
                        initials={(u.full_name || u.email).split(/[ @.]/).filter(Boolean).slice(0, 2).map(s => s[0]).join("").toUpperCase()}
                        size="sm"
                      />
                      <div className="col">
                        <div style={{ fontWeight: 500 }}>{u.full_name || (u.email.split("@")[0])}</div>
                        <div className="subtle" style={{ fontSize: 11.5 }}>
                          {isMe ? "you" : (u.email_confirmed ? "verified" : "pending verification")}
                        </div>
                      </div>
                    </div>
                  </td>
                  <td>
                    <select
                      className="field-input"
                      value={u.role === "user" ? "viewer" : u.role}
                      disabled={!canActOn(u) || busy[u.id]}
                      onChange={(e) => handleRoleChange(u, e.target.value)}
                      style={{ minWidth: 150, height: 32, fontSize: 13 }}
                    >
                      {allowed.map(r => (
                        <option key={r.value} value={r.value}>{r.label}</option>
                      ))}
                      {!allowed.find(r => r.value === u.role) && (
                        <option value={u.role}>{ROLE_BY_VALUE[u.role]?.label || u.role}</option>
                      )}
                    </select>
                    {lockReason && <div className="subtle" style={{ fontSize: 11, marginTop: 2 }}>{lockReason}</div>}
                  </td>
                  <td className="muted" style={{ fontSize: 12.5 }}>{fmt(u.last_sign_in_at)}</td>
                  <td className="muted" style={{ fontSize: 12.5 }}>{fmt(u.created_at)}</td>
                  <td className="muted" style={{ fontSize: 12.5, wordBreak: "break-all" }}>{u.email}</td>
                  <td style={{ textAlign: "right" }}>
                    <button
                      className="btn btn-quiet btn-sm"
                      onClick={() => setConfirmDelete(u)}
                      disabled={!canActOn(u) || busy[u.id]}
                      style={{ color: "#b91c1c" }}
                      title={lockReason || "Delete user"}
                    >
                      <Icon name="trash-2" size={12}/>ลบ
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {confirmDelete && (
        <div
          onClick={() => setConfirmDelete(null)}
          style={{
            position: "fixed", inset: 0, background: "rgba(31,27,22,0.5)",
            display: "grid", placeItems: "center", zIndex: 100,
          }}
        >
          <div
            onClick={(e) => e.stopPropagation()}
            style={{ background: "#fff", maxWidth: 440, width: "calc(100% - 32px)", borderRadius: 14, padding: 24, boxShadow: "0 20px 60px rgba(0,0,0,.2)" }}
          >
            <div style={{ fontFamily: "var(--font-serif)", fontSize: 22, fontWeight: 500, marginBottom: 8 }}>
              ลบบัญชี user?
            </div>
            <div className="muted" style={{ fontSize: 13.5, marginBottom: 18, lineHeight: 1.6 }}>
              จะลบ <strong>{confirmDelete.email}</strong> ({ROLE_BY_VALUE[confirmDelete.role]?.label || confirmDelete.role})
              ออกจากระบบถาวร — auth user + profile จะหายไป ไม่สามารถ revert ได้
            </div>
            <div className="row gap-8" style={{ justifyContent: "flex-end" }}>
              <button className="btn btn-ghost" onClick={() => setConfirmDelete(null)} disabled={busy[confirmDelete.id]}>
                ยกเลิก
              </button>
              <button
                className="btn btn-primary"
                style={{ background: "#b91c1c", borderColor: "#b91c1c" }}
                onClick={() => handleDelete(confirmDelete)}
                disabled={busy[confirmDelete.id]}
              >
                {busy[confirmDelete.id] === "deleting" ? "กำลังลบ…" : "ยืนยันลบถาวร"}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
