// page-settings.jsx — Conexões, Webhooks, Perfil com dados reais

const { useState: usSet, useEffect: ueSet } = React;

function PageSettings({ tenant, profile, onTenantUpdate }) {
  const [tab, setTab]   = usSet('connections');
  const [testResult, setTestResult] = usSet(null);
  const [testing, setTesting] = usSet(false);

  async function handleTest() {
    if (!tenant?.id) return;
    setTesting(true); setTestResult(null);
    try {
      const res = await SB.testIntegration(tenant.id);
      setTestResult(res);
    } catch { setTestResult({ nuvemshop: { status:'error' }, activecampaign: { status:'error' } }); }
    finally { setTesting(false); }
  }

  return (
    <div className="fade-up">
      <div className="page-head">
        <div>
          <h1 className="page-title">Configurações</h1>
          <p className="page-sub">Gerencie conexões, webhooks e dados da sua conta.</p>
        </div>
        <div className="page-actions">
          <button className="btn" onClick={handleTest} disabled={testing}>
            <iconify-icon icon={testing ? 'lucide:loader-circle' : 'lucide:activity'}
              style={testing ? { animation:'spin 1s linear infinite' } : {}} />
            {testing ? 'Testando…' : 'Testar integração'}
          </button>
        </div>
      </div>

      {testResult && (
        <div className="card" style={{ marginBottom:'var(--gap)', padding:16 }}>
          <div style={{ fontSize:13, fontWeight:700, marginBottom:10 }}>Resultado do teste</div>
          <div className="row gap-md" style={{ flexWrap:'wrap' }}>
            {[
              { label:'Nuvemshop', key:'nuvemshop' },
              { label:'ActiveCampaign', key:'activecampaign' },
              { label:'Webhooks', key:'webhooks' },
              { label:'Última execução', key:'last_execution' },
            ].map(item => {
              const r = testResult[item.key] ?? {};
              const s = r.status ?? 'error';
              return (
                <div key={item.key} style={{ padding:'10px 14px', borderRadius:'var(--r-md)', background:'var(--bg-elevated)', minWidth:160 }}>
                  <div className="muted" style={{ fontSize:10, textTransform:'uppercase', letterSpacing:1, marginBottom:4 }}>{item.label}</div>
                  <div className="row gap-sm">
                    <span style={{ width:8,height:8,borderRadius:'50%', background: s==='ok'?'var(--ok)':s==='warn'?'var(--warn)':'var(--err)' }} />
                    <span style={{ fontSize:12, fontWeight:700, color: s==='ok'?'var(--ok)':s==='warn'?'var(--warn)':'var(--err)' }}>
                      {s === 'ok' ? 'OK' : s === 'warn' ? 'Atenção' : 'Erro'}
                    </span>
                    {r.count !== undefined && <span className="muted" style={{fontSize:11}}>· {r.count} webhooks</span>}
                    {r.message && <span className="muted" style={{fontSize:11}}>· {r.message}</span>}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      <div className="tabs">
        {[['connections','Conexões'],['webhooks','Webhooks'],['profile','Perfil'],['danger','Avançado']].map(([id,l]) => (
          <button key={id} className={'tab '+(tab===id?'on':'')} onClick={() => setTab(id)}>{l}</button>
        ))}
      </div>

      {tab === 'connections' && <Connections tenant={tenant} />}
      {tab === 'webhooks' && <Webhooks tenant={tenant} />}
      {tab === 'profile' && <Profile profile={profile} />}
      {tab === 'danger' && <Danger tenant={tenant} />}
    </div>
  );
}

function Connections({ tenant }) {
  const [acUrl, setAcUrl] = usSet('');
  const [acKey, setAcKey] = usSet('');
  const [saving, setSaving] = usSet(false);
  const [saved, setSaved] = usSet(false);
  const [err, setErr] = usSet('');

  async function handleSaveAC() {
    if (!acUrl || !acKey) { setErr('Preencha URL e Key.'); return; }
    setSaving(true); setErr(''); setSaved(false);
    try {
      await SB.saveAcCredentials(tenant?.id, acUrl, acKey);
      setSaved(true);
      setAcUrl(''); setAcKey('');
    } catch { setErr('Erro ao salvar credenciais.'); }
    finally { setSaving(false); }
  }

  return (
    <div style={{ display:'grid', gap:'var(--gap)' }}>
      {/* Nuvemshop */}
      <div className="card">
        <div className="row gap-md" style={{ marginBottom:14 }}>
          <div style={{ width:48, height:48, borderRadius:12, background:'var(--bg-elevated)', display:'grid', placeItems:'center' }}>
            <iconify-icon icon="lucide:store" style={{ fontSize:24, color:'#3FB8E8' }} />
          </div>
          <div style={{ flex:1 }}>
            <div className="row gap-sm">
              <span style={{ fontSize:15, fontWeight:700 }}>Nuvemshop</span>
              {tenant?.nuvemshop_store_id
                ? <span className="tag tag-ok tag-dot">Conectado</span>
                : <span className="tag">Não conectado</span>}
            </div>
            <div className="muted" style={{ fontSize:12 }}>Token OAuth criptografado no vault. Nunca exposto.</div>
          </div>
        </div>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:14, padding:14, background:'var(--bg-base)', borderRadius:'var(--r-md)' }}>
          {[
            ['Loja', tenant?.store_name ?? '—'],
            ['Store ID', tenant?.nuvemshop_store_id ?? '—'],
            ['E-mail', tenant?.store_email ?? '—'],
          ].map(([k,v]) => (
            <div key={k}>
              <div className="muted" style={{ fontSize:10, textTransform:'uppercase', letterSpacing:1, fontWeight:700, marginBottom:4 }}>{k}</div>
              <div className="strong mono" style={{ fontSize:12 }}>{v}</div>
            </div>
          ))}
        </div>
      </div>

      {/* ActiveCampaign */}
      <div className="card">
        <div className="row gap-md" style={{ marginBottom:14 }}>
          <div style={{ width:48, height:48, borderRadius:12, background:'var(--bg-elevated)', display:'grid', placeItems:'center' }}>
            <iconify-icon icon="lucide:send" style={{ fontSize:24, color:'#25D682' }} />
          </div>
          <div style={{ flex:1 }}>
            <div className="row gap-sm">
              <span style={{ fontSize:15, fontWeight:700 }}>ActiveCampaign</span>
              <span className="tag">Atualizar credenciais</span>
            </div>
            <div className="muted" style={{ fontSize:12 }}>API URL e Key criptografadas no vault.</div>
          </div>
        </div>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12, marginBottom:12 }}>
          <div>
            <label className="tweaks-label" style={{ marginBottom:6 }}>URL da API</label>
            <input className="input" placeholder="https://suaconta.api-us1.com" value={acUrl} onChange={e => setAcUrl(e.target.value)} />
          </div>
          <div>
            <label className="tweaks-label" style={{ marginBottom:6 }}>API Key</label>
            <input className="input" type="password" placeholder="••••••••••••" value={acKey} onChange={e => setAcKey(e.target.value)} />
          </div>
        </div>
        {err && <div style={{ marginBottom:10, color:'var(--err)', fontSize:12 }}>{err}</div>}
        {saved && <div style={{ marginBottom:10, color:'var(--ok)', fontSize:12 }}>Credenciais salvas com sucesso.</div>}
        <button className="btn btn-primary" onClick={handleSaveAC} disabled={saving}>
          {saving ? <><iconify-icon icon="lucide:loader-circle" style={{ animation:'spin 1s linear infinite' }} /> Salvando…</> : <><iconify-icon icon="lucide:save" />Salvar credenciais</>}
        </button>
      </div>
    </div>
  );
}

function Webhooks({ tenant }) {
  const [webhooks, setWebhooks] = usSet([]);
  ueSet(() => { if (tenant?.id) SB.getWebhooks(tenant.id).then(setWebhooks).catch(() => {}); }, [tenant?.id]);

  return (
    <div className="card" style={{ padding:0, overflow:'hidden' }}>
      <div className="row" style={{ padding:'var(--card-pad)', justifyContent:'space-between' }}>
        <div>
          <div style={{ fontSize:14, fontWeight:700 }}>Webhooks da Nuvemshop</div>
          <div className="muted" style={{ fontSize:12 }}>Criados automaticamente no onboarding. Recriados em reinstalação.</div>
        </div>
      </div>
      <table className="tbl">
        <thead><tr><th>Tópico</th><th>Status</th><th>Criado em</th></tr></thead>
        <tbody>
          {webhooks.length === 0 && (
            <tr><td colSpan="3" style={{ textAlign:'center', padding:20, color:'var(--text-muted)' }}>
              Nenhum webhook registrado.
            </td></tr>
          )}
          {webhooks.map(w => (
            <tr key={w.id}>
              <td className="strong mono" style={{ fontSize:12 }}>{w.topic}</td>
              <td><span className="tag tag-ok tag-dot">{w.status}</span></td>
              <td className="muted">{new Date(w.created_at).toLocaleDateString('pt-BR')}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function Profile({ profile }) {
  const [name, setName] = usSet(profile?.full_name ?? '');
  const [company, setCompany] = usSet(profile?.company ?? '');
  const [phone, setPhone] = usSet(profile?.phone ?? '');
  const [saving, setSaving] = usSet(false);
  const [saved, setSaved] = usSet(false);

  async function handleSave() {
    setSaving(true);
    try { await SB.updateProfile({ full_name: name, company, phone }); setSaved(true); setTimeout(() => setSaved(false), 3000); }
    catch {}
    finally { setSaving(false); }
  }

  return (
    <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'var(--gap)', maxWidth:800 }}>
      <div><label className="tweaks-label" style={{ marginBottom:6 }}>Nome</label>
        <input className="input" value={name} onChange={e => setName(e.target.value)} /></div>
      <div><label className="tweaks-label" style={{ marginBottom:6 }}>Telefone</label>
        <input className="input" value={phone} onChange={e => setPhone(e.target.value)} /></div>
      <div><label className="tweaks-label" style={{ marginBottom:6 }}>Empresa</label>
        <input className="input" value={company} onChange={e => setCompany(e.target.value)} /></div>
      <div style={{ gridColumn:'1 / -1' }}>
        {saved && <div style={{ marginBottom:10, color:'var(--ok)', fontSize:12 }}>Perfil salvo.</div>}
        <button className="btn btn-primary" onClick={handleSave} disabled={saving}>
          <iconify-icon icon="lucide:save" />Salvar alterações
        </button>
      </div>
    </div>
  );
}

function Danger({ tenant }) {
  const [confirm, setConfirm] = usSet('');
  const [deleting, setDeleting] = usSet(false);

  async function handleDelete() {
    if (confirm !== 'EXCLUIR') return;
    setDeleting(true);
    try {
      await SB.callFunction('fn-delete-tenant', { tenant_id: tenant?.id });
      await SB.signOut();
    } catch { setDeleting(false); }
  }

  return (
    <div style={{ display:'grid', gap:'var(--gap)', maxWidth:720 }}>
      <div className="card" style={{ border:'1px solid var(--err)' }}>
        <div className="row gap-sm" style={{ marginBottom:8 }}>
          <iconify-icon icon="lucide:trash-2" style={{ color:'var(--err)' }} />
          <span style={{ fontWeight:700 }}>Excluir conta e dados (LGPD)</span>
        </div>
        <p className="secondary" style={{ fontSize:13, marginBottom:14 }}>
          Remove permanentemente seu tenant, credenciais, webhooks da Nuvemshop e todos os logs. Ação irreversível.
        </p>
        <div style={{ marginBottom:10 }}>
          <label className="tweaks-label" style={{ marginBottom:6 }}>Digite EXCLUIR para confirmar</label>
          <input className="input" value={confirm} onChange={e => setConfirm(e.target.value)} placeholder="EXCLUIR" />
        </div>
        <button className="btn" style={{ color:'var(--err)', borderColor:'var(--err)' }}
          onClick={handleDelete} disabled={confirm !== 'EXCLUIR' || deleting}>
          {deleting ? 'Excluindo…' : 'Excluir conta permanentemente'}
        </button>
      </div>
    </div>
  );
}

Object.assign(window, { PageSettings });
