// Cadastros reais por organização (Clientes, Equipes, Contratos, Financeiro). Lê e grava pelas tabelas com RLS da
// organização ativa; só mostra as colunas que existem no banco e confirma a gravação com a linha devolvida.
function RecordsScreen({ go, moduleId }) {
  const { PageHeader, Button, KpiCard, Input, Card, CardHeader, Badge, Drawer, DataField, Select, Alert, EmptyState } = window.VRticeDesignSystem_d763eb;
  const { toast } = useShell();
  const { can } = useAccess();
  const R = window.VxRecords, spec = R.SPECS[moduleId];
  const meta = window.VX_NAV.meta[moduleId] || {};
  const { loading: orgLoading, org } = useActiveOrg();
  const orgId = org && org.id;
  const [st, reload] = useRemote(() => orgId ? R.list(window.VxAuth.db(), spec, orgId) : [], [orgId, moduleId]);
  const refSpecs = spec.fields.filter(f => f.kind === 'ref');
  const [refs] = useRemote(async () => {
    const out = {};
    for (const f of refSpecs) { try { out[f.key] = orgId ? await R.list(window.VxAuth.db(), R.SPECS[f.ref], orgId) : []; } catch (e) { out[f.key] = null; } }
    return out;
  }, [orgId, moduleId]);
  const [q, setQ] = React.useState(''), [drawer, setDrawer] = React.useState(null), [confirm, setConfirm] = React.useState(false);
  const [busy, setBusy] = React.useState(false), [err, setErr] = React.useState(''), [fieldErr, setFieldErr] = React.useState({});
  React.useEffect(() => { setQ(''); setDrawer(null); setConfirm(false); }, [moduleId, orgId]);

  const rows = st.data || [];
  const refLabel = (f, id) => { const list = refs.data && refs.data[f.key]; if (!id) return '—'; const r = list && list.find(x => x.id === id); return r ? r[R.SPECS[f.ref].title] : 'Registro não visível'; };
  const money = v => v == null ? '—' : Number(v).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
  const fmtDate = v => v ? new Date(v + 'T00:00:00').toLocaleDateString('pt-BR') : '—';
  const show = (f, r) => {
    const v = r[f.key];
    if (f.kind === 'money') return money(v);
    if (f.kind === 'date') return fmtDate(v);
    if (f.kind === 'bool') return v ? 'Sim' : 'Não';
    if (f.kind === 'ref') return refLabel(f, v);
    if (f.kind === 'document') return v ? (v.length === 14 ? v.replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/, '$1.$2.$3/$4-$5') : v.replace(/^(\d{3})(\d{3})(\d{3})(\d{2})$/, '$1.$2.$3-$4')) : '—';
    return v == null || v === '' ? '—' : String(v);
  };
  const qq = q.trim().toLowerCase();
  const shown = rows.filter(r => !qq || spec.fields.some(f => f.kind !== 'ref' && String(show(f, r)).toLowerCase().includes(qq)));
  const cur = drawer && drawer.mode === 'view' ? rows.find(x => x.id === drawer.id) : null;
  const draft = drawer && drawer.mode === 'form' ? drawer.draft : null;
  const kpis = R.KPIS[moduleId](rows);

  const setD = (k, v) => { setErr(''); setFieldErr(e => ({ ...e, [k]: undefined })); setDrawer(d => ({ ...d, draft: { ...d.draft, [k]: v } })); };
  const blankDraft = () => Object.fromEntries(spec.fields.map(f => [f.key, f.default ?? (f.kind === 'bool' ? false : '')]));
  const toDraft = r => Object.fromEntries(spec.fields.map(f => [f.key, r[f.key] == null ? (f.kind === 'bool' ? false : '') : r[f.key]]));
  const openNew = () => { setErr(''); setFieldErr({}); setDrawer({ mode: 'form', draft: blankDraft() }); };
  const openEdit = r => { setErr(''); setFieldErr({}); setDrawer({ mode: 'form', id: r.id, draft: toDraft(r) }); };

  const save = async () => {
    setBusy(true); setErr(''); setFieldErr({});
    try {
      const saved = drawer.id ? await R.update(window.VxAuth.db(), spec, orgId, drawer.id, draft, rows.find(x => x.id === drawer.id)) : await R.create(window.VxAuth.db(), spec, orgId, draft);
      toast(drawer.id ? 'Alterações salvas' : 'Cadastro criado', 'ph-check-circle');
      setDrawer({ mode: 'view', id: saved.id }); reload();
    } catch (e) { setErr(e.message); if (e.fields) setFieldErr(e.fields); } finally { setBusy(false); }
  };
  const del = async () => {
    if (!confirm) return setConfirm(true);
    setBusy(true);
    try { await R.remove(window.VxAuth.db(), spec, orgId, cur.id); toast('Registro excluído', 'ph-check-circle'); setDrawer(null); setConfirm(false); reload(); }
    catch (e) { toast(e.message, 'ph-warning'); setConfirm(false); } finally { setBusy(false); }
  };
  const exportCsv = () => {
    const n = window.VxSafe.downloadCsv(moduleId + '.csv', spec.fields.map(f => f.label), shown.map(r => spec.fields.map(f => show(f, r))));
    toast('Planilha exportada (' + n + ' linhas)', 'ph-download-simple');
  };

  const columns = spec.fields.filter(f => f.kind !== 'ref' || refs.data).map((f, i) => ({
    key: f.key, label: f.label, strong: i === 0, mono: f.kind === 'money' || f.kind === 'date' || f.kind === 'document',
    align: f.kind === 'money' ? 'right' : undefined,
    sort: r => (f.kind === 'money' || f.kind === 'int') ? Number(r[f.key]) || 0 : String(show(f, r)),
    render: r => f.kind === 'bool' ? <Badge tone={r[f.key] ? 'success' : 'neutral'}>{r[f.key] ? 'Pago' : 'Em aberto'}</Badge> : show(f, r),
  }));

  const field = f => {
    const v = draft[f.key], e = fieldErr[f.key];
    if (f.kind === 'select') return <Select key={f.key} label={f.label} options={f.options} value={v} onChange={x => setD(f.key, x.target.value)} error={e} />;
    if (f.kind === 'bool') return <Select key={f.key} label={f.label} options={['Não', 'Sim']} value={v ? 'Sim' : 'Não'} onChange={x => setD(f.key, x.target.value === 'Sim')} />;
    if (f.kind === 'ref') {
      const list = (refs.data && refs.data[f.key]) || [], t = R.SPECS[f.ref].title;
      const labels = list.map(x => x[t] + ' · ' + x.id.slice(0, 4));
      const cur0 = list.find(x => x.id === v);
      return <Select key={f.key} label={f.label} options={['(nenhum)', ...labels]} value={cur0 ? cur0[t] + ' · ' + cur0.id.slice(0, 4) : '(nenhum)'} onChange={x => { const i = labels.indexOf(x.target.value); setD(f.key, i < 0 ? '' : list[i].id); }} error={e} />;
    }
    return <Input key={f.key} label={f.label + (f.required ? ' *' : '')} type={f.kind === 'date' ? 'date' : undefined} inputMode={f.kind === 'money' || f.kind === 'int' ? 'decimal' : undefined}
      value={v ?? ''} onChange={x => setD(f.key, x.target.value)} error={e} />;
  };

  const noun = spec.noun;
  const canCreate = can(spec.perm + '.create'), canEdit = can(spec.perm + '.edit'), canDelete = can(spec.perm + '.delete');
  const header = <PageHeader eyebrow={(meta.group || '').toUpperCase()} title={meta.label || noun[1]} description={'Registros reais da organização ativa. Os dados ficam no banco e respeitam as permissões do seu perfil.'}
    actions={<PBtn perm={spec.perm + '.create'} icon="ph-plus" onClick={openNew}>{'Novo(a) ' + noun[0]}</PBtn>} />;

  if (orgLoading || (st.loading && !st.data)) return <BlockGrid.Auto id={'rec-' + moduleId}>{header}<SkeletonPage /></BlockGrid.Auto>;
  if (!org) return <BlockGrid.Auto id={'rec-' + moduleId}>{header}<Alert tone="warning" title="Sem organização ativa">Não foi possível identificar a organização ativa. Entre novamente ou troque o contexto.</Alert></BlockGrid.Auto>;

  return (
    <BlockGrid.Auto id={'rec-' + moduleId}>
      {header}
      {st.error && <Alert tone="danger" title="Não foi possível carregar os registros">{st.error} <Button variant="secondary" size="sm" onClick={reload}>Tentar de novo</Button></Alert>}
      {!st.error && <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: 16 }}>
        {kpis.map(([l, v, c, kind]) => <KpiCard key={l} compact label={l} value={kind === 'money' ? money(v) : v} caption={c} />)}
      </div>}
      {moduleId === 'financeiro' && !st.error && <FinanceInsights rows={rows} contracts={refs.data && refs.data.contract_id} org={org} />}
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, alignItems: 'center' }}>
        <Input placeholder={'Buscar ' + noun[1]} value={q} onChange={e => setQ(e.target.value)} style={{ flex: '1 1 240px' }} />
        {spec.exportPerm && <PBtn perm={spec.exportPerm} variant="secondary" size="sm" icon="ph-download-simple" onClick={exportCsv} disabled={!shown.length}>Exportar</PBtn>}
      </div>
      <Card variant="flat" padding={0} gap={0} style={{ overflow: 'hidden' }}>
        <div style={{ padding: '22px 24px' }}><CardHeader size="sm" title={noun[1][0].toUpperCase() + noun[1].slice(1)} subtitle={org.name} action={<span style={{ fontSize: 13, color: 'var(--text-muted)' }}>{shown.length} de {rows.length}</span>} /></div>
        {shown.length
          ? <VxTable id={'rec-' + moduleId} minWidth={720} onRowClick={r => { setConfirm(false); setDrawer({ mode: 'view', id: r.id }); }} columns={columns} rows={shown} rowKey="id" />
          : <div style={{ padding: 24 }}><EmptyState variant="block" icon="ph-tray" title={rows.length ? 'Nada encontrado' : 'Nenhum registro ainda'}>{rows.length ? 'Ajuste a busca.' : (canCreate ? 'Use o botão acima para cadastrar o primeiro.' : 'Ainda não há registros nesta organização.')}</EmptyState></div>}
      </Card>
      {cur && <Drawer kicker={(meta.label || '').toUpperCase()} title={String(cur[spec.title] ?? '')} onClose={() => setDrawer(null)} footer={<>
        {canEdit && <Button style={{ flex: 1 }} onClick={() => openEdit(cur)}>Editar</Button>}
        {canDelete && <Button variant="danger" loading={busy} onClick={del}>{confirm ? 'Confirmar exclusão' : 'Excluir'}</Button>}
      </>}>
        {confirm && spec.deleteWarning && <Alert tone="warning" title="Atenção">{spec.deleteWarning}</Alert>}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '18px 16px' }}>
          {spec.fields.filter(f => f.key !== spec.title).map(f => <DataField key={f.key} label={f.label}>{show(f, cur)}</DataField>)}
          <DataField label="Criado em">{cur.created_at ? new Date(cur.created_at).toLocaleDateString('pt-BR') : '—'}</DataField>
        </div>
      </Drawer>}
      {draft && <Drawer kicker={drawer.id ? 'Editar cadastro' : 'Novo cadastro'} title={drawer.id ? String(draft[spec.title] || '') : 'Novo(a) ' + noun[0]} onClose={() => setDrawer(null)} footer={<><Button style={{ flex: 1 }} loading={busy} onClick={save}>Salvar</Button><Button variant="ghost" onClick={() => setDrawer(null)}>Cancelar</Button></>}>
        {err && <Alert tone="danger" title="Não foi possível salvar">{err}</Alert>}
        {spec.fields.map(field)}
      </Drawer>}
    </BlockGrid.Auto>
  );
}
window.RecordsScreen = RecordsScreen;
