// Settings screen — Conta + Histórico de cobrança.
// (API keys são internas/B2B — gerenciadas pelo admin, não aparecem aqui.)

function SettingsScreen({ tenant, onTenantUpdate, billing }) {
  const [tab, setTab] = useState('conta');
  const tabs = [
    { id: 'conta',    label: 'Conta' },
    { id: 'cobranca', label: 'Histórico de cobranças' },
  ];

  return (
    <div className="px-4 sm:px-8 py-5 sm:py-7 max-w-[1080px] mx-auto">
      <h1 className="text-[22px] font-bold text-ink-900 tracking-tightish">Configurações</h1>
      <p className="mt-1 text-[13px] text-ink-500">Conta do escritório e histórico de cobranças.</p>

      <div className="mt-5 border-b border-ink-200">
        <nav className="-mb-px flex gap-1 overflow-x-auto" style={{ scrollbarWidth: 'none' }}>
          {tabs.map((t) => {
            const active = tab === t.id;
            return (
              <button
                key={t.id}
                onClick={() => setTab(t.id)}
                className={`px-4 py-2.5 text-[13.5px] font-medium border-b-2 transition-colors whitespace-nowrap shrink-0 ${
                  active ? 'border-navy-800 text-navy-800' : 'border-transparent text-ink-500 hover:text-ink-900'
                }`}
              >
                {t.label}
              </button>
            );
          })}
        </nav>
      </div>

      <div className="mt-6">
        {tab === 'conta'    && <ContaTab tenant={tenant} onTenantUpdate={onTenantUpdate} />}
        {tab === 'cobranca' && <CobrancaTab billing={billing} />}
      </div>
    </div>
  );
}

function ContaTab({ tenant, onTenantUpdate }) {
  const [name, setName] = useState(tenant.name);
  const [email, setEmail] = useState(tenant.billing_email);
  const [saved, setSaved] = useState(false);
  const dirty = name !== tenant.name || email !== tenant.billing_email;

  const save = () => {
    onTenantUpdate({ ...tenant, name, billing_email: email });
    setSaved(true);
    setTimeout(() => setSaved(false), 2400);
  };

  const planLabel = tenant.plan_label || (tenant.plan_code ? tenant.plan_code.toUpperCase() : '—');

  return (
    <div className="bg-white rounded-lg border border-ink-200 shadow-card">
      <Section title="Dados do escritório" subtitle="Visíveis nos artefatos gerados e nas notas fiscais.">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
          <Field label="Nome do escritório">
            <TextInput value={name} onChange={(e) => setName(e.target.value)} />
          </Field>
          <Field label="E-mail de cobrança" hint="Recebe recibos e notas fiscais.">
            <TextInput type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
          </Field>
        </div>
      </Section>

      <Section title="Plano e status">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <InfoBlock label="Pacote atual" value={planLabel} hint="Tamanho da última recarga" />
          <InfoBlock label="Status" value={<TenantStatusBadge status={tenant.status} />} hint="Conta apta a criar novas análises" />
          <InfoBlock label="Cliente desde" value={fmtDate.format(new Date(tenant.created_at))} hint="Conta criada nesta data" />
        </div>
      </Section>

      <div className="px-6 py-4 border-t border-ink-200 flex items-center justify-between bg-ink-50/60 rounded-b-lg">
        <div className="text-[12.5px] text-ink-500">
          {saved && <span className="text-ok-700 inline-flex items-center gap-1.5"><Icon.Check /> Alterações salvas.</span>}
        </div>
        <div className="flex items-center gap-2">
          <Button variant="ghost" disabled={!dirty} onClick={() => { setName(tenant.name); setEmail(tenant.billing_email); }}>Descartar</Button>
          <Button disabled={!dirty} onClick={save}>Salvar alterações</Button>
        </div>
      </div>
    </div>
  );
}

function Section({ title, subtitle, children }) {
  return (
    <div className="px-6 py-5 border-b border-ink-100 last:border-b-0">
      <div className="mb-4">
        <h3 className="text-[14px] font-semibold text-ink-900">{title}</h3>
        {subtitle && <p className="mt-0.5 text-[12.5px] text-ink-500">{subtitle}</p>}
      </div>
      {children}
    </div>
  );
}

function InfoBlock({ label, value, hint }) {
  return (
    <div className="rounded-md border border-ink-200 px-4 py-3 bg-ink-50/50">
      <div className="text-[11px] uppercase tracking-tracker text-ink-500 font-medium">{label}</div>
      <div className="mt-1.5 text-[15px] font-semibold text-ink-900">{value}</div>
      {hint && <div className="mt-1 text-[11.5px] text-ink-500">{hint}</div>}
    </div>
  );
}

// ─── Billing tab ─────────────────────────────────────────────────────────────
function CobrancaTab({ billing }) {
  return (
    <div className="bg-white rounded-lg border border-ink-200 shadow-card overflow-hidden">
      <div className="px-6 py-4 border-b border-ink-200 flex items-center justify-between">
        <div>
          <h3 className="text-[14px] font-semibold text-ink-900">Histórico de cobranças</h3>
          <p className="mt-0.5 text-[12.5px] text-ink-500">Pagamentos e recargas de crédito.</p>
        </div>
      </div>
      <table className="w-full text-[13px]">
        <thead className="bg-ink-50 border-b border-ink-200">
          <tr className="text-left text-[11.5px] uppercase tracking-tracker text-ink-500 font-medium">
            <th className="px-6 py-2.5">Data</th>
            <th className="px-6 py-2.5 text-right">Valor</th>
            <th className="px-6 py-2.5">Método</th>
            <th className="px-6 py-2.5">Status</th>
            <th className="px-6 py-2.5 text-right">Comprovante</th>
          </tr>
        </thead>
        <tbody>
          {billing.map((b) => (
            <tr key={b.id} className="border-b border-ink-100 last:border-0">
              <td className="px-6 py-3.5 text-ink-700 tabular">{fmtDate.format(new Date(b.date))}</td>
              <td className="px-6 py-3.5 text-ink-900 tabular text-right font-semibold">{fmtBRL.format(b.amount)}</td>
              <td className="px-6 py-3.5 text-ink-700">{b.method}</td>
              <td className="px-6 py-3.5">
                <span className={`inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5 text-[11.5px] font-medium ${
                  b.status === 'PAGO'   ? 'bg-ok-50 text-ok-700 border-ok-200'
                : b.status === 'TRIAL'  ? 'bg-warn-50 text-warn-700 border-warn-200'
                                        : 'bg-ink-100 text-ink-700 border-ink-200'
                }`}>
                  {b.status}
                </span>
              </td>
              <td className="px-6 py-3.5 text-right">
                {b.status === 'PAGO'
                  ? <button onClick={() => alert('Comprovante PDF não implementado neste protótipo.')} className="text-navy-800 hover:underline text-[12.5px] font-medium">Ver comprovante</button>
                  : <span className="text-ink-400 text-[12.5px]">—</span>}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

window.SettingsScreen = SettingsScreen;
