// Team screen — Members list backed by the API. Invites + Roles still placeholders
// (those entities don't exist yet in the backend).
const ROLE_LABEL = {
  1: { en: "Owner",   es: "Propietario" },
  2: { en: "Admin",   es: "Admin" },
  3: { en: "Member",  es: "Miembro" },
  4: { en: "Billing", es: "Facturación" },
};

function TeamMemberDetailModal({ member, actorRole, onClose, lang, toast, onChanged }) {
  const [form, setForm] = React.useState(null);
  const [submitting, setSubmitting] = React.useState(false);

  React.useEffect(() => {
    if (member) {
      setForm({
        name: member.name || "",
        email: member.email || "",
        initials: member.initials || "",
        role: member.role,
        isActive: !!member.isActive,
      });
    }
  }, [member]);

  const open = !!member;
  // Lower role number = higher rank (Owner=1 … Billing=4). The current actor cannot
  // edit anyone with rank greater than or equal to theirs. If actorRole is null
  // (no logged-in member, e.g. System), there is no restriction.
  const readOnly = open && actorRole != null && member.role <= actorRole;
  const canSubmit = !readOnly && form && form.name.trim() && form.email.trim() && !submitting;

  const handleSave = async () => {
    if (!canSubmit) return;
    setSubmitting(true);
    try {
      await window.api.teamMembers.update(member.id, {
        name: form.name.trim(),
        email: form.email.trim(),
        role: parseInt(form.role, 10),
        isActive: !!form.isActive,
        initials: form.initials.trim() || null,
      });
      toast(lang === "es" ? `Miembro ${form.name.trim()} actualizado` : `Member ${form.name.trim()} updated`, "success");
      onChanged && onChanged();
      onClose();
    } catch (err) {
      toast(err.message || (lang === "es" ? "No se pudo guardar" : "Could not save"), "danger");
    } finally {
      setSubmitting(false);
    }
  };

  if (!open || !form) return null;

  const roleOptions = [
    { value: 1, label: ROLE_LABEL[1][lang] },
    { value: 2, label: ROLE_LABEL[2][lang] },
    { value: 3, label: ROLE_LABEL[3][lang] },
    { value: 4, label: ROLE_LABEL[4][lang] },
  ];

  return (
    <window.Modal open={open} onClose={onClose}
      title={lang === "es" ? "Editar miembro" : "Edit member"}
      subtitle={member.email}
      width={480}
      footer={
        <>
          <window.Btn variant="ghost" onClick={onClose} disabled={submitting}>
            {readOnly ? (lang === "es" ? "Cerrar" : "Close") : (lang === "es" ? "Cancelar" : "Cancel")}
          </window.Btn>
          {!readOnly && (
            <window.Btn variant="brand" onClick={handleSave} disabled={!canSubmit}>
              {submitting ? (lang === "es" ? "Guardando…" : "Saving…") : (lang === "es" ? "Guardar" : "Save")}
            </window.Btn>
          )}
        </>
      }
    >
      {readOnly && (
        <div style={{
          padding: "10px 12px",
          marginBottom: 12,
          borderRadius: 6,
          background: "var(--bg-muted)",
          border: "1px solid var(--border)",
          fontSize: 12,
          color: "var(--text-muted)",
        }}>
          {lang === "es"
            ? "No puedes editar a un miembro con tu mismo rango o superior."
            : "You can't edit a member with the same or higher rank."}
        </div>
      )}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <label className="field" style={{ gridColumn: "1 / -1" }}><span>{lang === "es" ? "Nombre" : "Name"} <i className="req">*</i></span>
          <input className="input" disabled={readOnly} value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} />
        </label>
        <label className="field"><span>Email <i className="req">*</i></span>
          <input className="input" type="email" disabled={readOnly} value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} />
        </label>
        <label className="field"><span>{lang === "es" ? "Iniciales" : "Initials"}</span>
          <input className="input" maxLength={4} disabled={readOnly} value={form.initials} onChange={e => setForm({ ...form, initials: e.target.value })} />
        </label>
        <div className="field"><span>{lang === "es" ? "Rol" : "Role"}</span>
          <window.Select disabled={readOnly} value={form.role} onChange={v => setForm({ ...form, role: v })} options={roleOptions} />
        </div>
        <div className="field"><span>{lang === "es" ? "Estado" : "Status"}</span>
          <window.Select
            disabled={readOnly}
            value={form.isActive ? "active" : "inactive"}
            onChange={v => setForm({ ...form, isActive: v === "active" })}
            options={[
              { value: "active",   label: lang === "es" ? "Activo"   : "Active" },
              { value: "inactive", label: lang === "es" ? "Inactivo" : "Inactive" },
            ]}
          />
        </div>
      </div>
    </window.Modal>
  );
}

function NewMemberModal({ open, onClose, lang, toast, actorRole, onCreated }) {
  // Roles strictly below the actor's. Owner (1) can invite Admin/Member/Billing,
  // Admin (2) can invite Member/Billing, etc. System (no actor) has no limit.
  const allowedRoles = React.useMemo(() => {
    const all = [1, 2, 3, 4];
    return actorRole == null ? all : all.filter(r => r > actorRole);
  }, [actorRole]);

  const [form, setForm] = React.useState({ name: "", email: "", initials: "", role: allowedRoles[0] });
  const [submitting, setSubmitting] = React.useState(false);

  React.useEffect(() => {
    if (open) setForm({ name: "", email: "", initials: "", role: allowedRoles[0] });
  }, [open, allowedRoles]);

  const canSubmit = form.name.trim() && form.email.trim() && allowedRoles.includes(parseInt(form.role, 10)) && !submitting;

  const handleCreate = async () => {
    if (!canSubmit) return;
    setSubmitting(true);
    try {
      await window.api.teamMembers.create({
        name: form.name.trim(),
        email: form.email.trim(),
        role: parseInt(form.role, 10),
        initials: form.initials.trim() || null,
      });
      toast(lang === "es" ? `Miembro ${form.name.trim()} invitado` : `Member ${form.name.trim()} invited`, "success");
      onCreated && onCreated();
      onClose();
    } catch (err) {
      toast(err.message || (lang === "es" ? "No se pudo invitar" : "Could not invite"), "danger");
    } finally {
      setSubmitting(false);
    }
  };

  if (!open) return null;

  const roleOptions = allowedRoles.map(r => ({ value: r, label: ROLE_LABEL[r][lang] }));

  return (
    <window.Modal open={open} onClose={onClose}
      title={lang === "es" ? "Invitar miembro" : "Invite member"}
      subtitle={lang === "es" ? "Añade a alguien a tu workspace." : "Add someone to your workspace."}
      width={480}
      footer={
        <>
          <window.Btn variant="ghost" onClick={onClose} disabled={submitting}>{lang === "es" ? "Cancelar" : "Cancel"}</window.Btn>
          <window.Btn variant="brand" onClick={handleCreate} disabled={!canSubmit}>
            {submitting ? (lang === "es" ? "Invitando…" : "Inviting…") : (lang === "es" ? "Invitar" : "Invite")}
          </window.Btn>
        </>
      }
    >
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <label className="field" style={{ gridColumn: "1 / -1" }}><span>{lang === "es" ? "Nombre" : "Name"} <i className="req">*</i></span>
          <input className="input" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} />
        </label>
        <label className="field"><span>Email <i className="req">*</i></span>
          <input className="input" type="email" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} placeholder="hola@ejemplo.com" />
        </label>
        <label className="field"><span>{lang === "es" ? "Iniciales" : "Initials"}</span>
          <input className="input" maxLength={4} value={form.initials} onChange={e => setForm({ ...form, initials: e.target.value })} />
        </label>
        <div className="field" style={{ gridColumn: "1 / -1" }}><span>{lang === "es" ? "Rol" : "Role"}</span>
          <window.Select value={form.role} onChange={v => setForm({ ...form, role: v })} options={roleOptions} />
        </div>
      </div>
    </window.Modal>
  );
}

window.TeamScreen = function TeamScreen({ t, lang, subTab }) {
  const sub = subTab || "members";
  const Icons = window.Icons;

  const [members, setMembers] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [refreshKey, setRefreshKey] = React.useState(0);
  const [openMember, setOpenMember] = React.useState(null);
  const [showInvite, setShowInvite] = React.useState(false);
  const [currentUserId, setCurrentUserId] = React.useState(() => window.getCurrentUserId());
  const toast = window.useToast();
  const refresh = React.useCallback(() => setRefreshKey(k => k + 1), []);

  React.useEffect(() => {
    if (sub !== "members") return;
    let cancelled = false;
    setLoading(true);
    window.api.teamMembers.list()
      .then(list => { if (!cancelled) { setMembers(list); setError(null); } })
      .catch(err => { if (!cancelled) setError(err.message); })
      .finally(() => { if (!cancelled) setLoading(false); });
    return () => { cancelled = true; };
  }, [sub, refreshKey]);

  // Re-evaluate edit permissions when the "Login as" picker changes.
  React.useEffect(() => {
    const onChange = () => setCurrentUserId(window.getCurrentUserId());
    window.addEventListener("current-user-changed", onChange);
    return () => window.removeEventListener("current-user-changed", onChange);
  }, []);

  const actorRole = React.useMemo(() => {
    if (!currentUserId) return null;
    const actor = members.find(m => m.id === currentUserId);
    return actor ? actor.role : null;
  }, [members, currentUserId]);

  // Owner (1) and Admin (2) can invite. System (no actor) also unrestricted.
  const canInvite = actorRole == null || actorRole <= 2;
  const handleInviteClick = () => {
    if (canInvite) setShowInvite(true);
    else toast(lang === "es"
      ? "No tienes permisos para invitar a nuevos miembros."
      : "You don't have permission to invite new members.", "warning");
  };

  return (
    <div className="page">
      <window.PageHeader
        title={lang === "es" ? "Equipo" : "Team"}
        subtitle={lang === "es"
          ? "Gestiona quién tiene acceso a tu workspace y qué pueden hacer."
          : "Manage who has access to your workspace and what they can do."}
        actions={
          sub === "members" ? (
            <window.Btn variant="brand" icon={Icons.Plus} onClick={handleInviteClick}>
              {lang === "es" ? "Invitar miembro" : "Invite member"}
            </window.Btn>
          ) : null
        }
      />

      {sub === "members" ? (
        <>
          <window.Toolbar>
            <span style={{ marginLeft: "auto", color: "var(--text-muted)", fontSize: 12 }}>
              {members.length} {lang === "es" ? "miembros" : "members"}
            </span>
          </window.Toolbar>

          <div className="card">
            <table className="tbl">
              <thead>
                <tr>
                  <th style={{ width: "32%" }}>{lang === "es" ? "Miembro" : "Member"}</th>
                  <th>{lang === "es" ? "Rol" : "Role"}</th>
                  <th>{lang === "es" ? "Estado" : "Status"}</th>
                  <th>{lang === "es" ? "Se unió" : "Joined"}</th>
                  <th style={{ width: 40 }}></th>
                </tr>
              </thead>
              <tbody>
                {loading && members.length === 0 && (
                  <tr><td colSpan={5} style={{ textAlign: "center", padding: 32, color: "var(--text-muted)" }}>Cargando…</td></tr>
                )}
                {error && (
                  <tr><td colSpan={5} style={{ textAlign: "center", padding: 32, color: "var(--danger)" }}>{error}</td></tr>
                )}
                {!loading && !error && members.map(m => (
                  <tr
                    key={m.id}
                    style={{ opacity: m.isActive ? 1 : 0.55, cursor: "default" }}
                    onDoubleClick={() => setOpenMember(m)}
                    title={lang === "es" ? "Doble click para editar" : "Double click to edit"}
                  >
                    <td>
                      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                        <window.Avatar initials={m.initials} size="sm" />
                        <div>
                          <div style={{ fontWeight: 500 }}>{m.name}</div>
                          <div className="mono" style={{ fontSize: 11, color: "var(--text-muted)" }}>{m.email}</div>
                        </div>
                      </div>
                    </td>
                    <td><span className="badge neutral">{(ROLE_LABEL[m.role] || {})[lang] || `Role ${m.role}`}</span></td>
                    <td>
                      <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12 }}>
                        <span style={{ width: 6, height: 6, borderRadius: "50%", background: m.isActive ? "var(--success)" : "var(--text-faint)" }} />
                        {m.isActive
                          ? (lang === "es" ? "Activo" : "Active")
                          : (lang === "es" ? "Inactivo" : "Inactive")}
                      </span>
                    </td>
                    <td className="num" style={{ color: "var(--text-muted)", fontSize: 12 }}>
                      {m.createdAt ? m.createdAt.slice(0, 10) : "—"}
                    </td>
                    <td><button className="icon-btn" style={{ width: 24, height: 24 }} disabled><Icons.MoreHorizontal /></button></td>
                  </tr>
                ))}
                {!loading && !error && members.length === 0 && (
                  <tr><td colSpan={5} style={{ textAlign: "center", padding: 32, color: "var(--text-muted)" }}>
                    {lang === "es" ? "No hay miembros aún." : "No members yet."}
                  </td></tr>
                )}
              </tbody>
            </table>
          </div>
        </>
      ) : (
        <div className="card" style={{ padding: 48, textAlign: "center" }}>
          <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 8 }}>
            {sub === "invites"
              ? (lang === "es" ? "Invitaciones" : "Invites")
              : (lang === "es" ? "Roles" : "Roles")}
          </div>
          <div style={{ fontSize: 12.5, color: "var(--text-muted)", maxWidth: 480, margin: "0 auto", lineHeight: 1.6 }}>
            {t("coming_soon_sub")}
          </div>
        </div>
      )}

      <TeamMemberDetailModal member={openMember} actorRole={actorRole} onClose={() => setOpenMember(null)} lang={lang} toast={toast} onChanged={refresh} />
      <NewMemberModal open={showInvite} onClose={() => setShowInvite(false)} lang={lang} toast={toast} actorRole={actorRole} onCreated={refresh} />
    </div>
  );
};

Object.assign(window, { TeamScreen: window.TeamScreen });
