// page-onboarding.jsx — Configuração inicial após cadastro
// Passo 1: Conectar Nuvemshop (OAuth) | Passo 2: Conectar ActiveCampaign

const { useState: useStateOnb, useEffect: useEffectOnb } = React;

const NUVEMSHOP_APP_ID = '16857';

function PageOnboarding({ tenant, session, onComplete }) {
  const [step, setStep] = useStateOnb(
    tenant?.nuvemshop_store_id ? 2 : 1
  );
  const [acUrl, setAcUrl]     = useStateOnb('');
  const [acKey, setAcKey]     = useStateOnb('');
  const [testing, setTesting] = useStateOnb(false);
  const [acOk, setAcOk]       = useStateOnb(false);
  const [error, setError]     = useStateOnb('');
  const [activating, setActivating] = useStateOnb(false);

  // Verificar se veio de um OAuth callback (query param tenant_id)
  useEffectOnb(() => {
    const params = new URLSearchParams(location.search);
    const returnedTenantId = params.get('tenant_id');
    if (returnedTenantId && tenant?.nuvemshop_store_id) {
      setStep(2);
    }
  }, [tenant]);

  function handleConnectNuvemshop() {
    // Redirect URI configurado no painel do app Nuvemshop — não passa como query param
    const installUrl = `https://www.nuvemshop.com.br/apps/${NUVEMSHOP_APP_ID}/authorize`;
    window.location.href = installUrl;
  }

  async function handleTestAC() {
    if (!acUrl || !acKey) { setError('Preencha a URL e a API Key.'); return; }
    setError(''); setTesting(true);
    try {
      // Chamar fn-validate-ac para testar as credenciais
      const res = await SB.callFunction('fn-validate-ac', {
        tenant_id: tenant?.id ?? 'new',
        ac_api_url: acUrl,
        ac_api_key: acKey,
        user_id: session?.user?.id,
      });
      if (res.valid) { setAcOk(true); }
      else { setError('Credenciais inválidas. Verifique a URL e a API Key.'); }
    } catch {
      setError('Erro ao testar conexão. Verifique os dados e tente novamente.');
    } finally {
      setTesting(false);
    }
  }

  async function handleActivate() {
    setActivating(true); setError('');
    try {
      const res = await SB.callFunction('fn-validate-ac', {
        tenant_id: tenant?.id,
        ac_api_url: acUrl,
        ac_api_key: acKey,
        save: true,
        nuvemshop_store_id: tenant?.nuvemshop_store_id,
        store_name: tenant?.store_name,
      });
      if (res.ok) {
        const updated = await SB.getTenant();
        onComplete(updated);
      } else {
        setError(res.error ?? 'Erro ao salvar credenciais.');
      }
    } catch {
      setError('Falha ao ativar integração.');
    } finally {
      setActivating(false);
    }
  }

  return (
    <div className="page-body" style={{ display:'flex', alignItems:'center', justifyContent:'center', minHeight:'calc(100vh - 56px)' }}>
      <div style={{ width:'100%', maxWidth:560 }}>

        {/* Progresso */}
        <div className="row" style={{ gap:8, marginBottom:36, justifyContent:'center' }}>
          {[1,2].map(n => (
            <React.Fragment key={n}>
              <div style={{
                width:32, height:32, borderRadius:'50%',
                background: step >= n ? 'var(--accent)' : 'var(--bg-elevated)',
                border: `1px solid ${step >= n ? 'var(--accent)' : 'var(--border)'}`,
                display:'grid', placeItems:'center',
                fontSize:13, fontWeight:800,
                color: step >= n ? 'var(--accent-fg)' : 'var(--text-muted)',
              }}>
                {step > n ? <iconify-icon icon="lucide:check" style={{ fontSize:14 }} /> : n}
              </div>
              {n < 2 && <div style={{ width:48, height:1, background:'var(--border)', marginTop:16 }} />}
            </React.Fragment>
          ))}
        </div>

        {/* ── Passo 1: Nuvemshop ── */}
        {step === 1 && (
          <div className="card" style={{ padding:32, textAlign:'center' }}>
            <div style={{
              width:64, height:64, borderRadius:16,
              background:'rgba(63,184,232,0.12)', border:'1px solid rgba(63,184,232,0.3)',
              display:'grid', placeItems:'center', margin:'0 auto 20px',
            }}>
              <iconify-icon icon="lucide:store" style={{ fontSize:28, color:'#3FB8E8' }} />
            </div>
            <h2 style={{ fontSize:22, fontWeight:800, marginBottom:8 }}>Conectar Nuvemshop</h2>
            <p className="secondary" style={{ marginBottom:28, fontSize:14, lineHeight:1.6 }}>
              Clique no botão abaixo para autorizar o SyncBridge a acessar
              sua loja Nuvemshop. Você será redirecionado e voltará aqui em segundos.
            </p>
            <button className="btn btn-primary" style={{ justifyContent:'center', padding:'12px 28px' }}
              onClick={handleConnectNuvemshop}>
              <iconify-icon icon="lucide:store" />
              Conectar minha loja Nuvemshop
              <iconify-icon icon="lucide:external-link" style={{ fontSize:14 }} />
            </button>
            <p className="muted" style={{ marginTop:16, fontSize:12 }}>
              Você será redirecionado para a Nuvemshop e depois voltará automaticamente.
            </p>
          </div>
        )}

        {/* ── Passo 2: ActiveCampaign ── */}
        {step === 2 && (
          <div className="card" style={{ padding:32 }}>
            {tenant?.nuvemshop_store_id && (
              <div style={{
                marginBottom:24, padding:'10px 14px',
                background:'var(--ok-soft)', border:'1px solid var(--ok)',
                borderRadius:'var(--r-md)', fontSize:13,
              }}>
                <div className="row gap-sm">
                  <iconify-icon icon="lucide:check-circle-2" style={{ color:'var(--ok)' }} />
                  <span style={{ fontWeight:700, color:'var(--ok)' }}>
                    Nuvemshop conectada — {tenant.store_name}
                  </span>
                </div>
              </div>
            )}

            <div style={{ textAlign:'center', marginBottom:28 }}>
              <div style={{
                width:64, height:64, borderRadius:16,
                background:'rgba(37,214,130,0.12)', border:'1px solid rgba(37,214,130,0.3)',
                display:'grid', placeItems:'center', margin:'0 auto 16px',
              }}>
                <iconify-icon icon="lucide:send" style={{ fontSize:28, color:'#25D682' }} />
              </div>
              <h2 style={{ fontSize:22, fontWeight:800, marginBottom:8 }}>Conectar ActiveCampaign</h2>
              <p className="secondary" style={{ fontSize:14 }}>
                Insira suas credenciais do ActiveCampaign para ativar a sincronização.
              </p>
            </div>

            <div style={{ marginBottom:14 }}>
              <label className="tweaks-label" style={{ marginBottom:6 }}>URL da API ActiveCampaign</label>
              <input className="input" placeholder="https://suaconta.api-us1.com"
                value={acUrl} onChange={e => setAcUrl(e.target.value)} />
              <div className="muted" style={{ fontSize:11, marginTop:4 }}>
                Encontre em ActiveCampaign → Configurações → API → URL
              </div>
            </div>

            <div style={{ marginBottom:20 }}>
              <label className="tweaks-label" style={{ marginBottom:6 }}>API Key</label>
              <input className="input" type="password" placeholder="Sua API Key"
                value={acKey} onChange={e => setAcKey(e.target.value)} />
              <div className="muted" style={{ fontSize:11, marginTop:4 }}>
                Encontre em ActiveCampaign → Configurações → API → Key
              </div>
            </div>

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

            {acOk && (
              <div style={{
                marginBottom:14, padding:'10px 12px',
                background:'var(--ok-soft)', border:'1px solid var(--ok)',
                borderRadius:'var(--r-md)', fontSize:13, 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:10 }}>
              {!acOk ? (
                <button className="btn btn-secondary" style={{ flex:1, justifyContent:'center' }}
                  onClick={handleTestAC} disabled={testing}>
                  {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" style={{ flex:1, justifyContent:'center' }}
                  onClick={handleActivate} disabled={activating}>
                  {activating
                    ? <><iconify-icon icon="lucide:loader-circle" style={{ animation:'spin 1s linear infinite' }} /> Ativando…</>
                    : <><iconify-icon icon="lucide:zap" />Ativar integração</>}
                </button>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { PageOnboarding });
