/* ANISAN — Usuários & permissões (exclusivo do Master). Habilita/desabilita
   quais abas cada usuário comum enxerga. O Master sempre vê tudo. Mapeará para
   auth.users + RLS no Supabase (papel + abas permitidas por usuário). */

function Usuarios({ currentUser, onVerComo }) {
  const store = window.useStore();
  const D = window.ANISAN_DATA;
  const data = store.data;
  const mobile = window.useIsMobile();

  const [dlg, setDlg] = React.useState(null);        // novo/editar usuário
  const [delUser, setDelUser] = React.useState(null);
  const [busy, setBusy] = React.useState(false);     // criação/exclusão via Edge Function
  const [erro, setErro] = React.useState("");
  const sb = window.ANISAN_SB;                        // se setado, estamos no modo Supabase

  React.useEffect(() => { window.lucide && window.lucide.createIcons(); });

  const SectionTitle = window.SectionTitle, Button = window.Button, Badge = window.Badge,
    Select = window.Select, Input = window.Input, Dialog = window.Dialog;

  const usuarios = data.usuarios || [];
  const abas = D.abas;

  const setAba = (uid, key, val) => store.set(d => {
    const u = d.usuarios.find(x => x.id === uid); if (!u) return;
    u.abas = Object.assign({}, u.abas); u.abas[key] = val;
  }, "usuarios");
  const setUnidade = (uid, un, val) => store.set(d => {
    const u = d.usuarios.find(x => x.id === uid); if (!u) return;
    u.unidades = Object.assign({}, u.unidades); u.unidades[un] = val;
  }, "usuarios");
  const setRole = (uid, role) => store.set(d => { const u = d.usuarios.find(x => x.id === uid); if (u) u.role = role; }, "usuarios");
  const todas = (uid, val) => store.set(d => {
    const u = d.usuarios.find(x => x.id === uid); if (!u) return;
    const m = {}; abas.forEach(a => m[a.key] = val); u.abas = m;
  }, "usuarios");
  const saveUser = async () => {
    const f = dlg;
    setErro("");
    // EDIÇÃO (usuário já existe): nome/email vão pro store e sincronizam via flush
    // (no Supabase, UPDATE em public.usuarios). Permissões são editadas na tabela.
    if (f.id) {
      store.set(d => { const u = d.usuarios.find(x => x.id === f.id); if (u) { u.nome = f.nome || u.nome; u.email = f.email || u.email; } }, "usuarios");
      setDlg(null);
      return;
    }
    // CRIAÇÃO de login.
    if (sb) {
      // Supabase: cria auth.users via Edge Function (service_role no backend); o
      // trigger espelha em public.usuarios (role comum). Depois re-hidrata.
      if (!f.email || !f.senha) { setErro("Informe e-mail e senha para o novo usuário."); return; }
      setBusy(true);
      try {
        const { data, error } = await sb.functions.invoke("admin-users", { body: { action: "create", email: f.email, password: f.senha, nome: f.nome } });
        if (error || (data && data.error)) { setErro((data && data.error) || "Falha ao criar usuário."); setBusy(false); return; }
        await window.ANISANStore.rehydrate();
      } catch (e) { setErro("Falha ao criar usuário."); setBusy(false); return; }
      setBusy(false); setDlg(null);
      return;
    }
    // Modo local (sem Supabase): comportamento antigo.
    store.set(d => {
      const abasDefault = {}; abas.forEach(a => abasDefault[a.key] = (a.key === "painel"));
      const unidadesDefault = {}; (D.units || []).forEach(un => unidadesDefault[un] = true);
      d.usuarios.push({ id: window.uid(), nome: f.nome || "Novo usuário", email: f.email || "", role: "comum", abas: abasDefault, unidades: unidadesDefault });
    }, "usuarios");
    setDlg(null);
  };
  const removeUser = async (uid) => {
    setErro("");
    if (sb) {
      setBusy(true);
      try {
        const { data, error } = await sb.functions.invoke("admin-users", { body: { action: "delete", id: uid } });
        if (error || (data && data.error)) { setErro((data && data.error) || "Falha ao excluir."); setBusy(false); return; }
        await window.ANISANStore.rehydrate();
      } catch (e) { setErro("Falha ao excluir."); setBusy(false); return; }
      setBusy(false); setDelUser(null);
      return;
    }
    store.set(d => { d.usuarios = d.usuarios.filter(x => x.id !== uid); }, "usuarios");
    setDelUser(null);
  };

  const Th = ({ children, center }) => (
    <th style={{ position: "sticky", top: 0, zIndex: 1, background: "var(--surface-2)", padding: "10px 8px", textAlign: center ? "center" : "left", fontFamily: "var(--font-mono)", fontSize: 9.5, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--muted)", fontWeight: 500, borderBottom: "1px solid var(--hairline)", whiteSpace: "nowrap" }}>{children}</th>
  );

  return (
    <div style={{ padding: mobile ? "18px 14px 40px" : "26px 32px 48px" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, flexWrap: "wrap", marginBottom: 8 }}>
        <SectionTitle style={{ margin: 0 }} meta="acesso · Master">Usuários & permissões</SectionTitle>
        <Button size="sm" variant="primary" onClick={() => setDlg({ nome: "", email: "" })}>+ Novo usuário</Button>
      </div>
      <p style={{ fontFamily: "var(--font-body)", fontSize: 12.5, color: "var(--muted)", lineHeight: 1.6, margin: "0 0 20px", maxWidth: 760 }}>
        Habilite ou desabilite quais <b style={{ color: "var(--paper)" }}>abas</b> e <b style={{ color: "var(--paper)" }}>unidades</b> cada usuário enxerga (colunas de unidade em destaque). O <b style={{ color: "var(--paper)" }}>Master</b> vê tudo e gerencia as permissões. O Consolidado só aparece para quem tem acesso a todas as unidades. Estas regras serão aplicadas no Supabase (papel + RLS por usuário).
      </p>

      <div style={{ overflowX: "auto", border: "1px solid var(--hairline)", borderRadius: "var(--radius)", background: "var(--surface)" }}>
        <table style={{ borderCollapse: "collapse", width: "100%", minWidth: 720 }}>
          <thead>
            <tr>
              <Th>Usuário</Th>
              <Th center>Papel</Th>
              {abas.map(a => <Th key={a.key} center>{a.label}</Th>)}
              {(D.units || []).map(un => <Th key={"u_" + un} center>{un}</Th>)}
              <Th center>Ações</Th>
            </tr>
          </thead>
          <tbody>
            {usuarios.map((u) => {
              const master = u.role === "master";
              const me = currentUser && u.id === currentUser.id;
              return (
                <tr key={u.id} style={{ borderTop: "1px solid var(--hairline)" }}>
                  <td style={{ padding: "12px 8px", minWidth: 200 }}>
                    <span style={{ display: "flex", alignItems: "center", gap: 10 }}>
                      <span style={{ width: 30, height: 30, borderRadius: "50%", flexShrink: 0, display: "grid", placeItems: "center", background: master ? "var(--brass)" : "var(--surface-2)", color: master ? "var(--ink)" : "var(--paper)", fontFamily: "var(--font-display)", fontSize: 13, fontWeight: 600, border: master ? "none" : "1px solid var(--hairline-strong)" }}>{(u.nome || "?").trim().charAt(0).toUpperCase()}</span>
                      <span style={{ minWidth: 0 }}>
                        <span style={{ display: "block", fontFamily: "var(--font-body)", fontSize: 13.5, color: "var(--paper)", whiteSpace: "nowrap" }}>{u.nome}{me ? "  ·  você" : ""}</span>
                        <span style={{ display: "block", fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--muted-2)", whiteSpace: "nowrap" }}>{u.email}</span>
                      </span>
                    </span>
                  </td>
                  <td style={{ padding: "12px 8px", textAlign: "center" }}>
                    {master
                      ? <Badge accent="var(--brass)" variant="tint">Master</Badge>
                      : <button onClick={() => setRole(u.id, "master")} title="Promover a Master" style={{ background: "none", border: "1px solid var(--hairline-strong)", color: "var(--muted)", borderRadius: "var(--radius-pill)", padding: "4px 11px", fontFamily: "var(--font-mono)", fontSize: 10.5, cursor: "pointer", whiteSpace: "nowrap" }}>Comum</button>}
                  </td>
                  {abas.map((a) => (
                    <td key={a.key} style={{ padding: "12px 8px", textAlign: "center" }}>
                      {master
                        ? <i data-lucide="check" style={{ width: 15, height: 15, strokeWidth: 2.2, color: "var(--jade)" }}></i>
                        : <Toggle on={!!(u.abas && u.abas[a.key])} onClick={() => setAba(u.id, a.key, !(u.abas && u.abas[a.key]))} />}
                    </td>
                  ))}
                  {(D.units || []).map((un) => (
                    <td key={"u_" + un} style={{ padding: "12px 8px", textAlign: "center", background: "var(--fill-accent)" }}>
                      {master
                        ? <i data-lucide="check" style={{ width: 15, height: 15, strokeWidth: 2.2, color: "var(--brass)" }}></i>
                        : <Toggle on={!!(u.unidades && u.unidades[un])} onClick={() => setUnidade(u.id, un, !(u.unidades && u.unidades[un]))} />}
                    </td>
                  ))}
                  <td style={{ padding: "12px 8px", textAlign: "center", whiteSpace: "nowrap" }}>
                    <span style={{ display: "inline-flex", gap: 6 }}>
                      {!master && <button title="Marcar todas" onClick={() => todas(u.id, true)} style={iconBtnU}><i data-lucide="check-check" style={{ width: 13, height: 13, strokeWidth: 1.8 }}></i></button>}
                      {!master && <button title="Limpar todas" onClick={() => todas(u.id, false)} style={iconBtnU}><i data-lucide="square" style={{ width: 13, height: 13, strokeWidth: 1.8 }}></i></button>}
                      <button title="Editar" onClick={() => setDlg({ id: u.id, nome: u.nome, email: u.email })} style={iconBtnU}><i data-lucide="pencil" style={{ width: 13, height: 13, strokeWidth: 1.7 }}></i></button>
                      {onVerComo && !me && <button title="Ver como este usuário" onClick={() => onVerComo(u.id)} style={iconBtnU}><i data-lucide="eye" style={{ width: 13, height: 13, strokeWidth: 1.7 }}></i></button>}
                      {!master && !me && <button title="Excluir" onClick={() => setDelUser(u)} style={Object.assign({}, iconBtnU, { color: "var(--muted-2)" })}><i data-lucide="trash-2" style={{ width: 13, height: 13, strokeWidth: 1.7 }}></i></button>}
                    </span>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <p style={{ fontFamily: "var(--font-body)", fontSize: 11.5, color: "var(--muted-2)", lineHeight: 1.6, margin: "16px 2px 0", maxWidth: 760 }}>
        Use o ícone <i data-lucide="eye" style={{ width: 12, height: 12, strokeWidth: 1.7, verticalAlign: "middle" }}></i> para pré-visualizar o sistema como aquele usuário (apenas as abas permitidas aparecem). Para voltar ao Master, use o aviso no topo.
      </p>

      {/* novo / editar usuário */}
      <Dialog open={!!dlg} title={dlg && dlg.id ? "Editar usuário" : "Novo usuário"} onClose={() => { if (!busy) { setErro(""); setDlg(null); } }} width={460}
        footer={<><Button onClick={() => { setErro(""); setDlg(null); }} disabled={busy}>Cancelar</Button><Button variant="solid" onClick={saveUser} disabled={busy}>{busy ? "Salvando…" : "Salvar"}</Button></>}>
        {dlg && (
          <div style={{ display: "grid", gap: 16 }}>
            <Input label="Nome" value={dlg.nome} onChange={(v) => setDlg({ ...dlg, nome: v })} icon="user" placeholder="Nome do usuário" />
            <Input label="E-mail" value={dlg.email} onChange={(v) => setDlg({ ...dlg, email: v })} icon="mail" placeholder="email@anisan.com.br" />
            {!dlg.id && sb && <Input label="Senha" type="password" value={dlg.senha || ""} onChange={(v) => setDlg({ ...dlg, senha: v })} icon="lock" placeholder="mín. 6 caracteres" />}
            {erro && <div role="alert" style={{ display: "flex", alignItems: "center", gap: 8, background: "var(--fill-accent)", border: "1px solid var(--clay)", borderRadius: "var(--radius-sm)", padding: "9px 12px" }}>
              <i data-lucide="alert-circle" style={{ width: 15, height: 15, strokeWidth: 1.8, color: "var(--clay)", flexShrink: 0 }}></i>
              <span style={{ fontFamily: "var(--font-body)", fontSize: 12.5, color: "var(--paper)" }}>{erro}</span>
            </div>}
            {!dlg.id && <p style={{ fontFamily: "var(--font-body)", fontSize: 12, color: "var(--muted)", margin: 0, lineHeight: 1.6 }}>{sb ? "Cria o login no Supabase (e-mail já confirmado). " : ""}O usuário entra como <b style={{ color: "var(--paper)" }}>Comum</b> vendo apenas o Painel. Ajuste as abas e unidades na tabela depois de criar.</p>}
          </div>
        )}
      </Dialog>

      {/* excluir usuário */}
      <Dialog open={!!delUser} title="Excluir usuário" onClose={() => { if (!busy) { setErro(""); setDelUser(null); } }} width={420}
        footer={<><Button onClick={() => { setErro(""); setDelUser(null); }} disabled={busy}>Cancelar</Button><Button variant="solid" accent="var(--clay)" onClick={() => removeUser(delUser.id)} disabled={busy}>{busy ? "Excluindo…" : "Excluir"}</Button></>}>
        {delUser && <div style={{ display: "grid", gap: 12 }}>
          <p style={{ fontFamily: "var(--font-body)", fontSize: 14, color: "var(--paper)", lineHeight: 1.6, margin: 0 }}>Excluir <b>{delUser.nome}</b>? {sb ? "O login é removido do Supabase (auth + perfil)." : "O acesso dele ao sistema é removido."}</p>
          {erro && <div role="alert" style={{ display: "flex", alignItems: "center", gap: 8, background: "var(--fill-accent)", border: "1px solid var(--clay)", borderRadius: "var(--radius-sm)", padding: "9px 12px" }}>
            <i data-lucide="alert-circle" style={{ width: 15, height: 15, strokeWidth: 1.8, color: "var(--clay)", flexShrink: 0 }}></i>
            <span style={{ fontFamily: "var(--font-body)", fontSize: 12.5, color: "var(--paper)" }}>{erro}</span>
          </div>}
        </div>}
      </Dialog>
    </div>
  );
}

function Toggle({ on, onClick }) {
  return (
    <button onClick={onClick} role="switch" aria-checked={on} style={{
      width: 38, height: 22, borderRadius: 11, border: "none", cursor: "pointer", padding: 0,
      background: on ? "var(--jade)" : "var(--hairline-strong)", position: "relative", transition: "background .15s ease", verticalAlign: "middle",
    }}>
      <span style={{ position: "absolute", top: 3, left: on ? 19 : 3, width: 16, height: 16, borderRadius: "50%", background: on ? "var(--paper)" : "var(--muted)", transition: "left .15s ease" }} />
    </button>
  );
}

const iconBtnU = { width: 26, height: 26, borderRadius: 7, background: "none", border: "1px solid var(--hairline)", display: "grid", placeItems: "center", cursor: "pointer", color: "var(--muted)" };

window.Usuarios = Usuarios;
