// Painel Administrativo Ezza CRM
// Acesso: /?admin=1 — a chave é validada NO SERVIDOR (nunca exposta no JS)
// Gerencia clientes, usuários e configurações

const { useState: useAdmState, useEffect: useAdmEffect } = React;

function AdminPanel() {
  const [authed, setAuthed] = useAdmState(false);
  const [keyInput, setKeyInput] = useAdmState('');
  const [adminKey, setAdminKey] = useAdmState(''); // chave validada, mantida só em memória
  const [tab, setTab] = useAdmState('clientes');
  const [clientes, setClientes] = useAdmState([]);
  const [loading, setLoading] = useAdmState(false);
  const [msg, setMsg] = useAdmState('');

  // Form novo cliente
  const [novoNome, setNovoNome] = useAdmState('');
  const [novoSlug, setNovoSlug] = useAdmState('');
  const [novoCor, setNovoCor] = useAdmState('#6C63FF');
  const [novoWaPhoneId, setNovoWaPhoneId] = useAdmState('');
  const [novoWaToken, setNovoWaToken] = useAdmState('');

  // Form novo usuário
  const [uNome, setUNome] = useAdmState('');
  const [uEmail, setUEmail] = useAdmState('');
  const [uSenha, setUSenha] = useAdmState('');
  const [uSlug, setUSlug] = useAdmState('');
  const [uPapel, setUPapel] = useAdmState('admin');

  const toast = (t) => { setMsg(t); setTimeout(() => setMsg(''), 3500); };

  const carregar = async (key) => {
    setLoading(true);
    try {
      const r = await fetch('/api/admin/clientes-lista', { headers: { 'x-admin-key': key || adminKey } });
      const d = await r.json();
      if (d.ok) setClientes(d.clientes);
    } catch (e) {}
    setLoading(false);
  };

  useAdmEffect(() => { if (authed) carregar(); }, [authed]);

  // Login: valida a chave NO SERVIDOR (tenta listar clientes com ela)
  const entrarAdmin = async (e) => {
    e.preventDefault();
    if (!keyInput.trim()) return;
    setLoading(true);
    try {
      const r = await fetch('/api/admin/clientes-lista', { headers: { 'x-admin-key': keyInput.trim() } });
      if (r.ok) {
        setAdminKey(keyInput.trim());
        setAuthed(true);
      } else {
        toast('❌ Chave incorreta');
      }
    } catch (err) {
      toast('❌ Erro de conexão');
    }
    setLoading(false);
  };

  const criarCliente = async (e) => {
    e.preventDefault();
    setLoading(true);
    try {
      const r = await fetch('/api/admin/clientes', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'x-admin-key': adminKey },
        body: JSON.stringify({
          nome: novoNome, slug: novoSlug, corPrimaria: novoCor,
          whatsappPhoneId: novoWaPhoneId || null,
          whatsappToken: novoWaToken || null,
        }),
      });
      const d = await r.json();
      if (d.ok) {
        toast(`✅ Cliente "${novoNome}" criado!`);
        setNovoNome(''); setNovoSlug(''); setNovoWaPhoneId(''); setNovoWaToken('');
        carregar();
      } else {
        toast(`❌ ${d.error}`);
      }
    } catch (e) { toast('❌ Erro de conexão'); }
    setLoading(false);
  };

  const criarUsuario = async (e) => {
    e.preventDefault();
    setLoading(true);
    try {
      const r = await fetch('/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ nome: uNome, email: uEmail, senha: uSenha, clienteSlug: uSlug, papel: uPapel }),
      });
      const d = await r.json();
      if (d.ok) {
        toast(`✅ Usuário "${uNome}" criado para ${uSlug}!`);
        setUNome(''); setUEmail(''); setUSenha(''); setUSlug('');
      } else {
        toast(`❌ ${d.error}`);
      }
    } catch (e) { toast('❌ Erro de conexão'); }
    setLoading(false);
  };

  const atualizarWa = async (clienteId, token, phoneId) => {
    const r = await fetch('/api/admin/clientes/whatsapp', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json', 'x-admin-key': adminKey },
      body: JSON.stringify({ clienteId, whatsappToken: token, whatsappPhoneId: phoneId }),
    });
    const d = await r.json();
    toast(d.ok ? '✅ WhatsApp atualizado!' : `❌ ${d.error}`);
    if (d.ok) carregar();
  };

  if (!authed) {
    return (
      <div style={{ minHeight: '100vh', display: 'grid', placeItems: 'center', background: 'oklch(0.97 0.015 250)', fontFamily: 'var(--font-ui)' }}>
        <div style={{ background: 'white', borderRadius: 24, padding: '48px 56px', width: 380, boxShadow: '0 32px 64px -24px rgba(20,30,60,.2)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 32 }}>
            <img src="assets/ezza-icon.svg" style={{ width: 36, height: 36 }} alt="" />
            <div>
              <div style={{ fontWeight: 700, fontSize: 17, letterSpacing: '-0.02em' }}>Ezza Admin</div>
              <div style={{ fontSize: 12, color: 'var(--ink-muted)' }}>Painel interno</div>
            </div>
          </div>
          <form onSubmit={entrarAdmin}>
            <label style={{ fontSize: 11.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--ink-muted)', display: 'block', marginBottom: 6 }}>Chave de admin</label>
            <input
              className="ezz-input" type="password"
              placeholder="••••••••••••••"
              value={keyInput} onChange={e => setKeyInput(e.target.value)}
              style={{ width: '100%', marginBottom: 16, fontSize: 14 }}
              autoFocus
            />
            <button type="submit" className="btn-primary" style={{ width: '100%', justifyContent: 'center' }}>Entrar</button>
          </form>
          {msg && <div style={{ marginTop: 14, fontSize: 13, color: msg.startsWith('❌') ? 'var(--danger)' : 'var(--ok)', textAlign: 'center' }}>{msg}</div>}
        </div>
      </div>
    );
  }

  return (
    <div style={{ minHeight: '100vh', background: 'oklch(0.97 0.01 250)', fontFamily: 'var(--font-ui)' }}>
      {/* Header */}
      <div style={{ background: 'white', borderBottom: '1px solid oklch(0.93 0.01 255)', padding: '0 32px', display: 'flex', alignItems: 'center', gap: 24, height: 60 }}>
        <img src="assets/ezza-icon.svg" style={{ width: 28, height: 28 }} alt="" />
        <span style={{ fontWeight: 700, fontSize: 15, letterSpacing: '-0.02em' }}>Ezza Admin</span>
        <div style={{ display: 'flex', gap: 4, marginLeft: 16 }}>
          {['clientes', 'usuarios', 'whatsapp'].map(t => (
            <button key={t} onClick={() => setTab(t)}
              style={{ padding: '6px 16px', borderRadius: 8, border: 'none', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, cursor: 'pointer',
                background: tab === t ? 'oklch(0.92 0.08 250)' : 'transparent',
                color: tab === t ? 'oklch(0.38 0.14 250)' : 'var(--ink-muted)' }}>
              {t === 'clientes' ? '🏢 Clientes' : t === 'usuarios' ? '👥 Usuários' : '💬 WhatsApp'}
            </button>
          ))}
        </div>
        <span style={{ marginLeft: 'auto', fontSize: 12, color: 'var(--ink-muted)' }}>
          {clientes.length} cliente{clientes.length !== 1 ? 's' : ''} cadastrado{clientes.length !== 1 ? 's' : ''}
        </span>
        <button onClick={carregar} style={{ background: 'oklch(0.96 0.01 250)', border: 'none', borderRadius: 8, padding: '6px 12px', fontSize: 12, cursor: 'pointer', fontFamily: 'inherit' }}>↻ Atualizar</button>
      </div>

      {msg && (
        <div style={{ background: msg.startsWith('❌') ? 'oklch(0.96 0.04 18)' : 'oklch(0.95 0.05 155)', color: msg.startsWith('❌') ? 'oklch(0.40 0.15 18)' : 'oklch(0.32 0.12 155)', padding: '12px 32px', fontSize: 13, fontWeight: 600 }}>
          {msg}
        </div>
      )}

      <div style={{ maxWidth: 1100, margin: '32px auto', padding: '0 24px', display: 'grid', gridTemplateColumns: tab === 'whatsapp' ? '1fr' : '1fr 1.4fr', gap: 24, alignItems: 'start' }}>

        {/* ── ABA CLIENTES ── */}
        {tab === 'clientes' && <>
          <div className="card">
            <div className="card-head"><div className="card-title">Novo cliente</div></div>
            <form onSubmit={criarCliente} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div className="field"><label className="field-lbl">Nome da empresa</label>
                <input className="ezz-input" value={novoNome} onChange={e => setNovoNome(e.target.value)} placeholder="Bio Pro Mais" required /></div>
              <div className="field"><label className="field-lbl">Slug (URL)</label>
                <div style={{ position: 'relative' }}>
                  <span style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', fontSize: 12, color: 'var(--ink-muted)', pointerEvents: 'none' }}>ezzacrm.com.br/</span>
                  <input className="ezz-input" value={novoSlug} onChange={e => setNovoSlug(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''))}
                    placeholder="biopromais" required style={{ paddingLeft: 120 }} />
                </div>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <div className="field"><label className="field-lbl">Cor principal</label>
                  <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                    <input type="color" value={novoCor} onChange={e => setNovoCor(e.target.value)} style={{ width: 40, height: 36, borderRadius: 8, border: '1px solid oklch(0.88 0.01 255)', cursor: 'pointer', padding: 2 }} />
                    <input className="ezz-input" value={novoCor} onChange={e => setNovoCor(e.target.value)} style={{ flex: 1 }} />
                  </div>
                </div>
                <div className="field"><label className="field-lbl">WhatsApp Phone ID</label>
                  <input className="ezz-input" value={novoWaPhoneId} onChange={e => setNovoWaPhoneId(e.target.value)} placeholder="1112814668..." /></div>
              </div>
              <div className="field"><label className="field-lbl">WhatsApp Token (opcional)</label>
                <input className="ezz-input" value={novoWaToken} onChange={e => setNovoWaToken(e.target.value)} placeholder="EAAiuAS..." /></div>
              <button type="submit" className="btn-primary" disabled={loading} style={{ justifyContent: 'center', marginTop: 4 }}>
                {loading ? 'Criando…' : '+ Criar cliente'}
              </button>
            </form>
          </div>

          <div className="card">
            <div className="card-head"><div className="card-title">Clientes cadastrados</div></div>
            {loading && <div style={{ color: 'var(--ink-muted)', fontSize: 13 }}>Carregando…</div>}
            {clientes.map(c => (
              <div key={c.id} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '12px 0', borderBottom: '1px solid oklch(0.94 0.01 255)' }}>
                <div style={{ width: 40, height: 40, borderRadius: 12, background: c.cor_primaria || '#6C63FF', display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                  <span style={{ fontSize: 14, fontWeight: 800, color: 'white' }}>{c.nome[0]}</span>
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 600, fontSize: 14 }}>{c.nome}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-muted)', fontFamily: 'var(--font-mono)' }}>{c.slug}.ezzacrm.com.br</div>
                </div>
                <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
                  {c.whatsapp_phone_id
                    ? <span className="pill pill-mint" style={{ fontSize: 10 }}>WhatsApp ✓</span>
                    : <span className="pill" style={{ fontSize: 10, background: 'oklch(0.94 0.02 18)', color: 'oklch(0.50 0.12 18)' }}>Sem WhatsApp</span>}
                  <span style={{ fontSize: 11, color: 'var(--ink-faint)' }}>ID {c.id}</span>
                </div>
              </div>
            ))}
            {!loading && clientes.length === 0 && <div style={{ color: 'var(--ink-muted)', fontSize: 13, padding: '16px 0' }}>Nenhum cliente cadastrado ainda.</div>}
          </div>
        </>}

        {/* ── ABA USUÁRIOS ── */}
        {tab === 'usuarios' && <>
          <div className="card">
            <div className="card-head"><div className="card-title">Novo usuário</div></div>
            <form onSubmit={criarUsuario} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <div className="field"><label className="field-lbl">Nome completo</label>
                <input className="ezz-input" value={uNome} onChange={e => setUNome(e.target.value)} placeholder="João Silva" required /></div>
              <div className="field"><label className="field-lbl">E-mail</label>
                <input className="ezz-input" type="email" value={uEmail} onChange={e => setUEmail(e.target.value)} placeholder="joao@empresa.com.br" required /></div>
              <div className="field"><label className="field-lbl">Senha inicial</label>
                <input className="ezz-input" type="password" value={uSenha} onChange={e => setUSenha(e.target.value)} placeholder="mínimo 6 caracteres" required minLength={6} /></div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <div className="field"><label className="field-lbl">Empresa (slug)</label>
                  <select className="ezz-input" value={uSlug} onChange={e => setUSlug(e.target.value)} required style={{ appearance: 'auto' }}>
                    <option value="">Selecionar...</option>
                    {clientes.map(c => <option key={c.id} value={c.slug}>{c.nome}</option>)}
                  </select>
                </div>
                <div className="field"><label className="field-lbl">Papel</label>
                  <select className="ezz-input" value={uPapel} onChange={e => setUPapel(e.target.value)} style={{ appearance: 'auto' }}>
                    <option value="admin">Admin</option>
                    <option value="usuario">Usuário</option>
                    <option value="vendedor">Vendedor</option>
                  </select>
                </div>
              </div>
              <button type="submit" className="btn-primary" disabled={loading} style={{ justifyContent: 'center', marginTop: 4 }}>
                {loading ? 'Criando…' : '+ Criar usuário'}
              </button>
            </form>
          </div>

          <div className="card">
            <div className="card-head"><div className="card-title">Clientes disponíveis</div></div>
            {clientes.map(c => (
              <div key={c.id} style={{ padding: '10px 0', borderBottom: '1px solid oklch(0.94 0.01 255)', fontSize: 13 }}>
                <span style={{ fontWeight: 600 }}>{c.nome}</span>
                <span style={{ color: 'var(--ink-muted)', marginLeft: 8, fontFamily: 'var(--font-mono)', fontSize: 11 }}>slug: {c.slug}</span>
              </div>
            ))}
          </div>
        </>}

        {/* ── ABA WHATSAPP ── */}
        {tab === 'whatsapp' && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24 }}>
            {clientes.map(c => (
              <ClienteWaCard key={c.id} cliente={c} onSave={atualizarWa} toast={toast} />
            ))}
            {clientes.length === 0 && <div className="card" style={{ gridColumn: '1/-1' }}><p style={{ color: 'var(--ink-muted)' }}>Nenhum cliente cadastrado.</p></div>}
          </div>
        )}
      </div>
    </div>
  );
}

function ClienteWaCard({ cliente, onSave, toast }) {
  const [token, setToken] = useAdmState(cliente.whatsapp_token || '');
  const [phoneId, setPhoneId] = useAdmState(cliente.whatsapp_phone_id || '');
  const [saving, setSaving] = useAdmState(false);

  const save = async () => {
    setSaving(true);
    await onSave(cliente.id, token, phoneId);
    setSaving(false);
  };

  return (
    <div className="card">
      <div className="card-head">
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ width: 36, height: 36, borderRadius: 10, background: cliente.cor_primaria || '#6C63FF', display: 'grid', placeItems: 'center' }}>
            <span style={{ fontSize: 14, fontWeight: 800, color: 'white' }}>{cliente.nome[0]}</span>
          </div>
          <div>
            <div className="card-title" style={{ fontSize: 14 }}>{cliente.nome}</div>
            <div style={{ fontSize: 11, color: 'var(--ink-muted)', fontFamily: 'var(--font-mono)' }}>{cliente.slug}</div>
          </div>
        </div>
        {cliente.whatsapp_phone_id
          ? <span className="pill pill-mint" style={{ fontSize: 10 }}>✓ Configurado</span>
          : <span style={{ fontSize: 11, color: 'oklch(0.55 0.12 18)', fontWeight: 600 }}>⚠ Sem WhatsApp</span>}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        <div className="field"><label className="field-lbl">Phone ID</label>
          <input className="ezz-input" value={phoneId} onChange={e => setPhoneId(e.target.value)} placeholder="1112814668574225" />
        </div>
        <div className="field"><label className="field-lbl">Token de acesso</label>
          <input className="ezz-input" value={token} onChange={e => setToken(e.target.value)} placeholder="EAAiuAS..." type="password" />
        </div>
        <button onClick={save} disabled={saving} className="btn-primary" style={{ justifyContent: 'center' }}>
          {saving ? 'Salvando…' : '💾 Salvar WhatsApp'}
        </button>
      </div>
    </div>
  );
}

window.AdminPanel = AdminPanel;
