const TENANT_STATUSES = [
  { key: 'active',    label: 'Ativo',    tone: 'emerald' },
  { key: 'trial',     label: 'Trial',    tone: 'amber' },
  { key: 'suspended', label: 'Suspenso', tone: 'coral' },
];

function ScreenTenants() {
  const [tenants, setTenants] = useState([]);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState(null);
  const [createModal, setCreateModal] = useState(false);

  useEffect(() => { loadTenants(); }, []);

  const loadTenants = async () => {
    setLoading(true);
    setErr(null);
    try {
      const data = await window.scpDb.tenants.list();
      setTenants(data);
    } catch (e) {
      setErr(e.message || 'Falha ao carregar assinantes');
    } finally {
      setLoading(false);
    }
  };

  const statusTone = (s) => TENANT_STATUSES.find(x => x.key === s)?.tone || 'fg';
  const statusLabel = (s) => TENANT_STATUSES.find(x => x.key === s)?.label || s;

  const counts = tenants.reduce((acc, t) => ({ ...acc, [t.status]: (acc[t.status] || 0) + 1 }), {});

  const handleDelete = async (t) => {
    const msg = `APAGAR DEFINITIVAMENTE o assinante "${t.name}"?\n\nIsso apaga TODOS os dados dele: produtos, fornecedores, cotações, pedidos, estoque, usuários. Os usuários do auth ficam órfãos (você precisa apagar manualmente).\n\nEsta ação NÃO pode ser desfeita. Para confirmar, digite o nome exato da empresa abaixo:`;
    const typed = window.prompt(msg, '');
    if (typed === null) return;
    if (typed.trim() !== t.name) {
      window.scpToast('Nome não confere — exclusão cancelada', { kind: 'amber' });
      return;
    }
    try {
      await window.scpDb.tenants.remove(t.id);
      await loadTenants();
      window.scpToast('Assinante apagado', { kind: 'amber', sub: t.name });
    } catch (e) {
      window.scpToast('Erro ao apagar', { kind: 'coral', sub: e.message });
    }
  };

  const handleEditNotes = async (t) => {
    const current = t.notes || '';
    const next = window.prompt(`Notas internas de "${t.name}":\n\nEdite abaixo (Ctrl+Enter ou Enter pra salvar, Cancelar pra desistir).`, current);
    if (next === null) return; // cancelou
    if (next === current) return; // sem mudança
    try {
      await window.scpDb.tenants.update(t.id, { notes: next.trim() || null });
      await loadTenants();
      window.scpToast('Notas atualizadas', { kind: 'emerald', sub: t.name });
    } catch (e) {
      window.scpToast('Erro ao salvar notas', { kind: 'coral', sub: e.message });
    }
  };

  const handleSetStatus = async (t, newStatus) => {
    const verb = newStatus === 'active' ? 'reativar' : 'suspender';
    if (!confirm(`Deseja ${verb} "${t.name}"?`)) return;
    try {
      await window.scpDb.tenants.setStatus(t.id, newStatus);
      await loadTenants();
      window.scpToast(`Assinante ${newStatus === 'active' ? 'reativado' : 'suspenso'}`, { kind: newStatus === 'active' ? 'emerald' : 'amber', sub: t.name });
    } catch (e) {
      window.scpToast('Erro ao mudar status', { kind: 'coral', sub: e.message });
    }
  };

  return (
    <div className="scp-screen scp-fade-in">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <div>
          <h2 style={{ margin: 0, fontSize: 22, fontWeight: 600 }}>Assinantes</h2>
          <p style={{ margin: '4px 0 0', fontSize: 13, color: 'var(--fg-3)' }}>
            {counts.active || 0} ativos · {counts.trial || 0} trial · {counts.suspended || 0} suspensos
          </p>
        </div>
        <Btn kind="primary" icon={<Icon.Plus size={16}/>} onClick={() => setCreateModal(true)}>
          Novo assinante
        </Btn>
      </div>

      {err && (
        <Card style={{ padding: 12, marginBottom: 14, borderColor: 'oklch(0.42 0.10 25 / .55)', background: 'oklch(0.26 0.08 25 / .25)' }}>
          <strong style={{ color: 'oklch(0.88 0.14 25)', fontSize: 13 }}>Falha:</strong>{' '}
          <span style={{ color: 'var(--fg-2)', fontSize: 12.5 }}>{err}</span>
        </Card>
      )}

      <table className="scp-table">
        <thead>
          <tr>
            <th>Empresa</th><th>CNPJ</th><th>Status</th><th>Usuários</th>
            <th>Último acesso</th><th>Criado em</th><th>Notas</th><th></th>
          </tr>
        </thead>
        <tbody>
          {loading && <tr><td colSpan={8} style={{ padding: 24, textAlign: 'center', color: 'var(--fg-3)', fontSize: 13 }}>Carregando…</td></tr>}
          {!loading && tenants.length === 0 && (
            <tr><td colSpan={8} style={{ padding: 24, textAlign: 'center', color: 'var(--fg-3)', fontSize: 13 }}>
              Nenhum assinante cadastrado. Clique em "Novo assinante" para começar.
            </td></tr>
          )}
          {!loading && tenants.map(t => (
            <tr key={t.id}>
              <td><div className="em">{t.name}</div><div style={{ fontSize: 11, color: 'var(--fg-3)' }}>{t.city || '—'}</div></td>
              <td style={{ fontFamily: 'JetBrains Mono', fontSize: 11.5, color: 'var(--fg-3)' }}>{t.cnpj || '—'}</td>
              <td><Badge tone={statusTone(t.status)}>{statusLabel(t.status)}</Badge></td>
              <td style={{ fontSize: 13 }}>{t.users}</td>
              <td style={{ fontSize: 12, color: 'var(--fg-3)' }}>
                {t.last_seen_at ? new Date(t.last_seen_at).toLocaleString('pt-BR') : 'nunca'}
              </td>
              <td style={{ fontSize: 12, color: 'var(--fg-3)' }}>
                {new Date(t.created_at).toLocaleDateString('pt-BR')}
              </td>
              <td style={{ fontSize: 12, color: 'var(--fg-3)', maxWidth: 220 }} title={t.notes || ''}>
                {t.notes
                  ? (t.notes.length > 40 ? t.notes.slice(0, 40) + '…' : t.notes)
                  : <em style={{ color: 'var(--fg-4)' }}>—</em>}
              </td>
              <td>
                <div style={{ display: 'flex', gap: 4 }}>
                  <Btn kind="ghost" size="sm" onClick={() => handleEditNotes(t)} title="Editar notas">Notas</Btn>
                  {t.status !== 'suspended' && (
                    <Btn kind="ghost" size="sm" onClick={() => handleSetStatus(t, 'suspended')}>Suspender</Btn>
                  )}
                  {t.status === 'suspended' && (
                    <Btn kind="ghost" size="sm" onClick={() => handleSetStatus(t, 'active')}>Reativar</Btn>
                  )}
                  <Btn kind="ghost" size="sm" onClick={() => handleDelete(t)} title="Apagar definitivamente" style={{ color: 'oklch(0.82 0.14 25)' }}>
                    <Icon.Trash size={13}/>
                  </Btn>
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>

      {createModal && (
        <NewTenantModal onClose={() => setCreateModal(false)} onCreated={async () => { setCreateModal(false); await loadTenants(); }} />
      )}
    </div>
  );
}

function NewTenantModal({ onClose, onCreated }) {
  const [name, setName] = useState('');
  const [cnpj, setCnpj] = useState('');
  const [email, setEmail] = useState('');
  const [city, setCity] = useState('');
  const [address, setAddress] = useState('');
  const [status, setStatus] = useState('trial');
  const [notes, setNotes] = useState('');
  const [adminName, setAdminName] = useState('');
  const [adminEmail, setAdminEmail] = useState('');
  const [adminPwd, setAdminPwd] = useState(generateTempPassword());
  const [saving, setSaving] = useState(false);

  const emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  const canSubmit = !saving
    && name.trim().length >= 2
    && adminName.trim().length >= 2
    && emailRe.test(adminEmail.trim())
    && adminPwd.length >= 8;

  const submit = async () => {
    if (!canSubmit) return;
    setSaving(true);
    try {
      const result = await window.scpDb.tenants.create({
        company: { name: name.trim(), cnpj: cnpj.trim(), email: email.trim(), city: city.trim(), address: address.trim(), status, notes: notes.trim() || null },
        admin: { name: adminName.trim(), email: adminEmail.trim().toLowerCase(), password: adminPwd },
      });
      const sub = result.needsConfirmation
        ? `Admin precisa confirmar e-mail. Senha temporária: ${adminPwd}`
        : `Senha temporária do admin: ${adminPwd}`;
      window.scpToast(`Assinante criado · ${result.company.name}`, { kind: 'emerald', sub });
      await onCreated();
    } catch (e) {
      window.scpToast('Erro ao criar', { kind: 'coral', sub: e.message });
    } finally {
      setSaving(false);
    }
  };

  return ReactDOM.createPortal(
    <div className="scp-modal-mask" onClick={window.scpConfirmCloseModal(onClose)}>
      <div className="scp-modal" style={{ width: 680 }} onClick={e => e.stopPropagation()}>
        <div className="scp-modal-head">
          <h3>Novo assinante</h3>
          <IconBtn icon={<Icon.X size={14}/>} size="sm" onClick={onClose}/>
        </div>
        <div className="scp-modal-body" style={{ padding: '18px 22px' }}>
          <h4 style={{ margin: '0 0 10px', fontSize: 13 }}>Dados da empresa</h4>
          <div className="scp-sfield-grid">
            <label className="scp-field"><span>Razão social *</span><Input value={name} onChange={e => setName(e.target.value)} autoFocus /></label>
            <label className="scp-field"><span>CNPJ</span><Input value={cnpj} onChange={e => setCnpj(e.target.value)} /></label>
            <label className="scp-field"><span>E-mail</span><Input type="email" value={email} onChange={e => setEmail(e.target.value)} /></label>
            <label className="scp-field"><span>Cidade / UF</span><Input value={city} onChange={e => setCity(e.target.value)} /></label>
            <label className="scp-field" style={{ gridColumn: '1 / -1' }}><span>Endereço</span><Input value={address} onChange={e => setAddress(e.target.value)} /></label>
            <label className="scp-field">
              <span>Status inicial</span>
              <select className="scp-input" value={status} onChange={e => setStatus(e.target.value)}>
                <option value="trial">Trial</option>
                <option value="active">Ativo</option>
              </select>
            </label>
            <label className="scp-field" style={{ gridColumn: '1 / -1' }}>
              <span>Notas internas <small style={{ color: 'var(--fg-3)', fontSize: 11, fontWeight: 400 }}>(só o revendedor vê)</small></span>
              <textarea
                className="scp-input"
                rows={2}
                value={notes}
                onChange={e => setNotes(e.target.value)}
                placeholder="Ex.: forma de cobrança, contato comercial, observações da negociação…"
                style={{ resize: 'vertical', minHeight: 50, padding: '8px 12px', fontFamily: 'inherit', fontSize: 13 }}
              />
            </label>
          </div>

          <h4 style={{ margin: '18px 0 10px', fontSize: 13 }}>Primeiro administrador</h4>
          <div className="scp-sfield-grid">
            <label className="scp-field"><span>Nome *</span><Input value={adminName} onChange={e => setAdminName(e.target.value)} /></label>
            <label className="scp-field"><span>E-mail *</span><Input type="email" value={adminEmail} onChange={e => setAdminEmail(e.target.value)} /></label>
            <label className="scp-field" style={{ gridColumn: '1 / -1' }}>
              <span>Senha temporária *</span>
              <div style={{ display: 'flex', gap: 8 }}>
                <Input style={{ flex: 1 }} value={adminPwd} onChange={e => setAdminPwd(e.target.value)} />
                <Btn kind="ghost" size="sm" onClick={() => setAdminPwd(generateTempPassword())} type="button">Gerar nova</Btn>
              </div>
              <small style={{ fontSize: 11, color: 'var(--fg-3)' }}>Mínimo 8 caracteres. Anote ou copie antes de fechar — só aparece uma vez.</small>
            </label>
          </div>
        </div>
        <div className="scp-modal-foot">
          <span>Status inicial: <strong>{status === 'trial' ? 'Trial' : 'Ativo'}</strong></span>
          <div style={{ display: 'flex', gap: 8 }}>
            <Btn kind="ghost" onClick={onClose}>Cancelar</Btn>
            <Btn kind="primary" disabled={!canSubmit} onClick={submit} icon={<Icon.Check size={14}/>}>
              {saving ? 'Criando…' : 'Criar assinante'}
            </Btn>
          </div>
        </div>
      </div>
    </div>,
    document.body
  );
}

window.ScreenTenants = ScreenTenants;
