/* ============================================================
   P&L App (Lite) · Money Out (from the US demo's)
   ------------------------------------------------------------
   One amount per bill: the full amount paid. Sales tax on a bill is part of the cost
   in the US, so there is no tax column.
   What changed from the demo (briefs/65-lite-feature-list.md):
   - Status is Paid / Unpaid; Overdue shows by itself once the due date has passed.
   - Job, Split, payment method, date paid, approved by and truck are paid-plan features:
     the Job column shows locked, the rest sit in the form's locked strip.
   - Description and Notes are one Note. No Import (locked), no Approve.
   ============================================================ */
const OUT_LOCKED_FIELDS = ['job', 'split across categories', 'payment method', 'date paid', 'approved by', 'truck', 'part payments', 'the document'];

function PlataForm({ open, onClose, editing }) {
  const blank = { data: todayISO(), categorie: '', furnizor: '', nrFactura: '', status: 'Paid', notes: '', sumaNeta: '', dataScadenta: '' };
  const [f, setF] = useState(blank);
  useEffect(() => { if (open) setF(editing ? { ...editing, status: editing.status === 'Paid' ? 'Paid' : 'Unpaid', notes: editing.notes || '', dataScadenta: editing.dataScadenta || '' } : blank); }, [open, editing]);

  const set = (k, v) => setF(p => ({ ...p, [k]: v }));
  const net = parseFloat(String(f.sumaNeta).replace(/,/g, '')) || 0;
  const valid = f.furnizor.trim() && net > 0 && f.data && f.categorie;

  const save = () => {
    const payload = { data: f.data, furnizor: f.furnizor, categorie: f.categorie, nrFactura: f.nrFactura, status: f.status, notes: f.notes, sumaNeta: net, dataScadenta: f.dataScadenta || null };
    if (editing) updatePlata(editing.id, payload);
    else addPlata(payload);
    onClose();
  };

  return (
    <Modal open={open} onClose={onClose} icon="out" width={680}
      title={editing ? 'Edit money out' : 'Add an expense'}
      subtitle="The full amount paid. Sales tax on a bill is part of the cost."
      footer={<>
        <Button variant="ghost" onClick={onClose}>Cancel</Button>
        <Button variant="primary" icon="check" disabled={!valid} onClick={save}>{editing ? 'Save changes' : 'Add expense'}</Button>
      </>}>
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <Field label="Date" required><Input type="date" value={f.data} onChange={e => set('data', e.target.value)} /></Field>
        <Field as="div" label="Category" required hint={f.categorie ? (catTypeOf(f.categorie) === 'overhead' ? 'An overhead: running the business.' : 'A direct cost: the cost of doing the work.') : null}>
          <PickOrAdd value={f.categorie} options={DB.categorii.map(c => c.name)} onChange={v => set('categorie', v)}
                     onCreate={name => addCategorieNamed(name, 'expense')} placeholder="Pick the category…" createLabel="Create the category" />
        </Field>
        <Field as="div" label="Vendor" required className="sm:col-span-2">
          <PickOrAdd value={f.furnizor} options={namesOf('furnizor')} onChange={v => set('furnizor', v)}
                     onCreate={name => addName('furnizor', name)} placeholder="Pick or type the vendor…" createLabel="Add the vendor" />
        </Field>
        <Field label="Bill #"><Input placeholder="Number on the bill" value={f.nrFactura} onChange={e => set('nrFactura', e.target.value)} /></Field>
        <Field label="Amount" required><NumberInput placeholder="0.00" value={f.sumaNeta} onChange={e => set('sumaNeta', e.target.value)} /></Field>
        <Field label="Status" hint="Overdue shows by itself once the due date has passed."><Select value={f.status} onChange={e => set('status', e.target.value)}>{STATUS_PICK.map(s => <option key={s}>{s}</option>)}</Select></Field>
        <Field label="Due date" hint="When the vendor wants paying"><Input type="date" value={f.dataScadenta} onChange={e => set('dataScadenta', e.target.value)} /></Field>
        <Field label="Note" className="sm:col-span-2"><Textarea rows={2} placeholder="What it was for…" value={f.notes} onChange={e => set('notes', e.target.value)} /></Field>
        <div className="sm:col-span-2"><LockedStrip items={OUT_LOCKED_FIELDS} /></div>
      </div>
    </Modal>
  );
}

function Plati() {
  const db = useDB();
  // Filters, search, sort: kept while the page is open, empty after a reload. All the logic is in filters.jsx.
  const [fs, setFs] = useFilterState('plati');
  const [formOpen, setFormOpen] = useState(false);
  const [editing, setEditing] = useState(null);
  const [del, setDel] = useState(null);
  const [detail, setDetail] = useState(null);
  const trade = showTrade();

  const rows = visibleRows(db.plati, fs, 'plati');
  const t = totals(rows);
  const hasFilters = (fs.filters || []).length > 0 || !!fs.q;
  const reset = () => setFs({ filters: [], q: '', sort: fs.sort });
  const openAdd = () => { setEditing(null); setFormOpen(true); };

  return (
    <div className="flex flex-col gap-4">
      <Card className="px-4 py-3.5">
        <FilterBar table="plati" state={fs} setState={setFs} rows={db.plati}
          searchPlaceholder="Search vendor, bill, amount…"
          onDownload={() => downloadFilteredCSV('plati', rows, fs)} downloadCount={rows.length}
          right={<><LockedButton feature="import" icon="upload">Import</LockedButton><Button variant="primary" icon="plus" onClick={openAdd}>Add expense</Button></>} />
      </Card>

      <Card className="overflow-hidden">
        <div className="overflow-x-auto scroll-area">
          <table className="w-full min-w-[960px] border-collapse" style={{ tableLayout: 'fixed' }}>
            <colgroup><col style={{ width: '52px' }} /><col style={{ width: '108px' }} /><col style={{ width: '22%' }} />{trade && <col style={{ width: '14%' }} />}<col style={{ width: '17%' }} /><col style={{ width: '112px' }} /><col style={{ width: '120px' }} /><col style={{ width: '120px' }} /><col style={{ width: '76px' }} /></colgroup>
            <thead>
              <tr className="text-[11px] uppercase tracking-wide text-muted bg-[#F6F8F3]">
                <th className="text-left font-600 py-3 pl-5">#</th>
                <SortHeader className="px-3" sortKey="data" state={fs} setState={setFs}>Date</SortHeader>
                <SortHeader className="px-3" sortKey="furnizor" state={fs} setState={setFs}>Vendor</SortHeader>
                {trade && <LockedHeader feature="jobs" className="px-3">Job</LockedHeader>}
                <SortHeader className="px-3" sortKey="categorie" state={fs} setState={setFs}>Category</SortHeader>
                <SortHeader className="px-3" sortKey="nrFactura" state={fs} setState={setFs}>Bill #</SortHeader>
                <SortHeader className="px-3" sortKey="sumaNeta" state={fs} setState={setFs} align="right">Amount</SortHeader>
                <SortHeader className="px-3" sortKey="status" state={fs} setState={setFs}>Status</SortHeader>
                <th className="py-3 pr-4"></th>
              </tr>
            </thead>
            <tbody>
              {rows.map((r, i) => {
                const flagged = r.needsReview || missingDueDate(r, 'out');
                return (
                <tr key={r.id} className="group border-t border-line transition-colors hover:bg-[#F6F8F3]" style={r.needsReview ? { background: '#FDF1F0' } : undefined}>
                  <td className="py-2.5 pl-5">
                    <span className="flex items-center gap-2 text-[12px] text-muted num">
                      {flagged ? <span className="w-2 h-2 rounded-full shrink-0" style={{ background: 'var(--neg)' }} title={r.reviewReason || 'Unpaid with no due date'} /> : <span className="w-2 h-2 shrink-0" />}
                      {i + 1}
                    </span>
                  </td>
                  <td className="py-1.5 px-3 text-[13px] num text-ink whitespace-nowrap"><EditCell type="date" required value={r.data} onSave={val => updatePlata(r.id, { data: val })}>{fmtDate(r.data)}</EditCell></td>
                  <td className="py-1.5 px-3">
                    <EditCell type="pick" required value={r.furnizor} options={namesOf('furnizor')} onCreate={name => addName('furnizor', name)} onSave={val => val && updatePlata(r.id, { furnizor: val })}>
                      <div className="flex items-center gap-2 min-w-0 w-full"><span className="text-[13px] font-medium text-ink truncate">{r.furnizor}</span></div>
                    </EditCell>
                  </td>
                  {trade && <td className="py-1.5 px-3"><LockedCell i={i + 2} feature="jobs" /></td>}
                  <td className="py-1.5 px-3">
                    <EditCell type="pick" required value={r.categorie} options={DB.categorii.map(c => c.name)} onCreate={name => addCategorieNamed(name, 'expense')} onSave={val => val && updatePlata(r.id, { categorie: val })}>
                      {r.categorie
                        ? <span className="text-[12px] text-ink px-2 h-6 inline-flex items-center rounded-md bg-[#F1FBD4] whitespace-nowrap max-w-full min-w-0"><span className="truncate">{r.categorie}</span></span>
                        : <span className="text-[12px] font-600" style={{ color: 'var(--neg)' }}>Pick a category</span>}
                    </EditCell>
                  </td>
                  <td className="py-1.5 px-3">
                    <EditCell value={r.nrFactura || ''} onSave={val => updatePlata(r.id, { nrFactura: val })}>
                      <span className="block text-[12.5px] num text-muted truncate" title={r.nrFactura || ''}>{r.nrFactura || '—'}</span>
                    </EditCell>
                  </td>
                  <td className="py-1.5 px-3 text-right">
                    <EditCell type="number" align="right" value={r.sumaNeta} onSave={val => updatePlata(r.id, { sumaNeta: Math.round(val * 100) / 100 })}>
                      <span className="text-[13px] num text-ink font-medium whitespace-nowrap">{moneyUSD(r.sumaNeta)}</span>
                    </EditCell>
                  </td>
                  <td className="py-2.5 px-3"><InlineStatus value={r.status} options={STATUS_PICK} onChange={val => updatePlata(r.id, { status: val })} /></td>
                  <td className="py-2.5 pr-4"><div className="flex items-center justify-end gap-0.5">
                    <IconButton icon="arrowRight" title="Open: every detail" onClick={() => setDetail(r)} />
                    <IconButton icon="trash" tone="neg" title="Delete" onClick={() => setDel(r)} />
                  </div></td>
                </tr>
                );
              })}
            </tbody>
          {rows.length > 0 && (
            <tfoot><tr className="border-t border-line bg-[#F6F8F3]">
              <td colSpan={trade ? 6 : 5} className="py-3.5 pl-5 align-top text-[12.5px] text-muted">{rows.length} {plural(rows.length, 'row')}</td>
              <td className="px-3 py-3.5 align-top text-right"><div className="text-[10.5px] uppercase tracking-wide text-muted">Amount</div><div className="num text-[13px] font-700 text-ink">{moneyUSD(t.net)}</div></td>
              <td className="px-3 py-3.5 align-top text-left"><div className="text-[10.5px] uppercase tracking-wide text-muted">Paid</div><div className="num text-[13px] font-600 text-ink">{moneyUSD(rows.reduce((s, r) => s + platitEfectiv(r), 0))}</div></td>
              <td></td>
            </tr></tfoot>
          )}
          </table>
        </div>
        {rows.length === 0 && <EmptyState icon="out" title={hasFilters ? 'Nothing found' : 'No expenses yet'} message={hasFilters ? 'Nothing matches the current filters.' : 'Add your first bill or receipt to start.'} action={hasFilters ? <Button variant="soft" icon="refresh" onClick={reset}>Clear filters</Button> : <Button variant="primary" icon="plus" onClick={openAdd}>Add expense</Button>} />}
      </Card>

      <PlataForm open={formOpen} onClose={() => setFormOpen(false)} editing={editing} />
      <TransactionDetail record={detail} kind="out" onClose={() => setDetail(null)} onDelete={r => { setDetail(null); setDel(r); }} />
      <ConfirmDialog open={!!del} onClose={() => setDel(null)} onConfirm={() => deletePlata(del.id)}
        title="Delete this expense?" message={del ? `The bill from ${del.furnizor} (${moneyUSD(del.sumaNeta)}) will be deleted for good.` : ''} confirmLabel="Delete" />
    </div>
  );
}

Object.assign(window, { Plati, PlataForm });
