// ac-credentials-form.jsx — Formulário compartilhado de credenciais ActiveCampaign

const { useState: useAC, useEffect: ueAC } = React;

function ACCredentialsForm({ tenant, session, onSuccess, showTitle = true }) {
  const [acUrl, setAcUrl]     = useAC('');
  const [acKey, setAcKey]     = useAC('');
  const [phase, setPhase]     = useAC('idle'); // idle | testing | saving | done | error
  const [error, setError]     = useAC('');
  const [tested, setTested]   = useAC(false);

  async function handleTest() {
    if (!acUrl || !acKey) { setError('Preencha a URL e a API Key.'); return; }
    setError(''); setPhase('testing'); setTested(false);
    try {
      const res = await SB.callFunction('fn-validate-ac', {
        ac_api_url: acUrl.trim(),
        ac_api_key: acKey.trim(),
      });
      if (res?.valid) {
        setTested(true);
        setPhase('idle');
      } else {
        setError('Credenciais inválidas. Verifique a URL e a API Key.');
        setPhase('error');
      }
    } catch (e) {
      setError('Erro ao conectar. Verifique a URL e a Key.');
      setPhase('error');
    }
  }

  async function handleSave() {
    setPhase('saving'); setError('');
    try {
      const res = await SB.callFunction('fn-validate-ac', {
        tenant_id: tenant?.id,
        ac_api_url: acUrl.trim(),
        ac_api_key: acKey.trim(),
        save: true,
        nuvemshop_store_id: tenant?.nuvemshop_store_id,
        store_name: tenant?.store_name,
        user_id: session?.user?.id,
      });
      if (res?.ok) {
        setPhase('done');
        setAcUrl(''); setAcKey('');
        if (onSuccess) {
          const updated = await SB.getTenant();
          onSuccess(updated);
        }
      } else {
        setError(res?.error ?? 'Erro ao salvar credenciais.');
        setPhase('error');
      }
    } catch (e) {
      setError('Falha ao salvar. Tente novamente.');
      setPhase('error');
    }
  }

  const loading = phase === 'testing' || phase === 'saving';

  return (
    <div>
      {showTitle && (
        <div style={{ marginBottom: 16 }}>
          <div style={{ fontSize: 14, fontWeight: 700, marginBottom: 4 }}>ActiveCampaign</div>
          <div className="muted" style={{ fontSize: 12 }}>API URL e Key criptografadas no vault.</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); setTested(false); }} />
        </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); setTested(false); }} />
        </div>
      </div>

      {error && (
        <div style={{ marginBottom: 10, padding: '8px 12px', borderRadius: 'var(--r-md)', fontSize: 12,
          background: 'var(--err-soft)', border: '1px solid var(--err)', color: 'var(--err)' }}>
          {error}
        </div>
      )}

      {phase === 'done' && (
        <div style={{ marginBottom: 10, padding: '8px 12px', borderRadius: 'var(--r-md)', fontSize: 12,
          background: 'var(--ok-soft)', border: '1px solid var(--ok)', color: 'var(--ok)' }}>
          <div className="row gap-sm">
            <iconify-icon icon="lucide:check-circle-2" />
            Credenciais salvas com sucesso.
          </div>
        </div>
      )}

      {tested && phase !== 'done' && (
        <div style={{ marginBottom: 10, padding: '8px 12px', borderRadius: 'var(--r-md)', fontSize: 12,
          background: 'var(--ok-soft)', border: '1px solid var(--ok)', color: 'var(--ok)' }}>
          <div className="row gap-sm">
            <iconify-icon icon="lucide:check-circle-2" />
            ActiveCampaign validado com sucesso!
          </div>
        </div>
      )}

      <div className="row" style={{ gap: 8 }}>
        {!tested ? (
          <button className="btn" onClick={handleTest} disabled={loading}>
            {phase === 'testing'
              ? <><iconify-icon icon="lucide:loader-circle" style={{ animation: 'spin 1s linear infinite' }} /> Testando…</>
              : <><iconify-icon icon="lucide:plug" />Testar conexão</>}
          </button>
        ) : (
          <button className="btn btn-primary" onClick={handleSave} disabled={loading}>
            {phase === 'saving'
              ? <><iconify-icon icon="lucide:loader-circle" style={{ animation: 'spin 1s linear infinite' }} /> Salvando…</>
              : <><iconify-icon icon="lucide:save" />Salvar credenciais</>}
          </button>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { ACCredentialsForm });
