/* ============================================================
   P&L App (Lite) · Money In (from the US demo's)
   ------------------------------------------------------------
   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.
   - A Category column (income categories: Sales, Other income...). The demo had none.
   - Job and Type are paid-plan features: the Job column shows locked; Type, payment method
     and the rest sit in the form's locked strip. Description and Notes are one Note.
   - No Import: the button stays, locked. No Approve: "To review" clears when the row is fixed.
   ============================================================ */
const IN_LOCKED_FIELDS = ['job', 'type (deposit, change order...)', 'retainage', 'payment method', 'date received', 'part payments', 'the document'];
/* A new invoice starts with the sales tax rate this company used last (8.25% before its first one). */
function lastRateUsed() { const r = DB.incasari.slice().sort((a, b) => String(b.createdAt || '').localeCompare(String(a.createdAt || '')))[0]; return r ? r.cotaTva : 8.25; }

/* The sales tax rate: Houston's 8.25%, 0% (not taxable), or another rate typed in. */
function RateField({ value, onChange }) {
  const usual = usualVatRates();
  const [other, setOther] = useState(!usual.includes(Number(value)));
  // a row with an unusual rate opened for editing: show the rate typed in, not the first option
  useEffect(() => { if (value !== '' && !usual.includes(Number(value))) setOther(true); }, [value]);
  return (
    <div className="flex gap-2">
      <Select value={other ? 'other' : String(value)} onChange={e => { if (e.target.value === 'other') setOther(true); else { setOther(false); onChange(Number(e.target.value)); } }}>
        <option value="8.25">8.25%</option>
        <option value="0">0% (not taxable)</option>
        <option value="other">Another rate…</option>
      </Select>
      {other && <NumberInput className="max-w-[96px]" placeholder="%" value={value} onChange={e => onChange(e.target.value)} />}
    </div>
  );
}

function IncasareForm({ open, onClose, editing }) {
  const blank = { data: todayISO(), client: '', categorie: (DB.categoriiIn[0] || {}).name || '', nrFactura: '', status: 'Unpaid', notes: '', sumaNeta: '', cotaTva: lastRateUsed(), termenPlata: 30, dataScadenta: addDays(todayISO(), 30) };
  const [f, setF] = useState(blank);
  const [touchedScad, setTouchedScad] = useState(false);

  useEffect(() => {
    if (open) {
      setF(editing ? { ...editing, status: editing.status === 'Paid' ? 'Paid' : 'Unpaid', notes: editing.notes || '', termenPlata: editing.termenPlata == null ? '' : editing.termenPlata } : blank);
      setTouchedScad(!!editing);
    }
  }, [open, editing]);

  const set = (k, v) => setF(p => {
    const n = { ...p, [k]: v };
    if ((k === 'data' || k === 'termenPlata') && !touchedScad) n.dataScadenta = addDays(k === 'data' ? v : n.data, parseInt(k === 'termenPlata' ? v : n.termenPlata, 10) || 0);
    return n;
  });

  const net = parseFloat(String(f.sumaNeta).replace(/,/g, '')) || 0;
  const rate = parseFloat(String(f.cotaTva).replace(/,/g, '')) || 0;
  const tva = tvaOf(net, rate);
  const brut = net + tva;
  const valid = f.client.trim() && net > 0 && f.data && rate >= 0;

  const save = () => {
    const payload = { data: f.data, client: f.client, categorie: f.categorie, nrFactura: f.nrFactura, status: f.status, notes: f.notes,
      sumaNeta: net, cotaTva: rate, dataScadenta: f.dataScadenta || null };
    if (editing) updateIncasare(editing.id, payload);
    else addIncasare(payload);
    onClose();
  };

  return (
    <Modal open={open} onClose={onClose} icon="in" width={680}
      title={editing ? 'Edit money in' : 'Add money in'}
      subtitle="Amounts are before sales tax. The sales tax and the total are worked out for you."
      footer={<>
        <Button variant="ghost" onClick={onClose}>Cancel</Button>
        <Button variant="primary" icon="check" disabled={!valid} onClick={save}>{editing ? 'Save changes' : 'Add money in'}</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">
          <PickOrAdd value={f.categorie} options={DB.categoriiIn.map(c => c.name)} onChange={v => set('categorie', v)}
                     onCreate={name => addCategorieNamed(name, 'income')} emptyLabel="— No category —" placeholder="Pick the category…" createLabel="Create the category" />
        </Field>
        <Field as="div" label="Customer" required className="sm:col-span-2">
          <PickOrAdd value={f.client} options={namesOf('client')} onChange={v => set('client', v)}
                     onCreate={name => addName('client', name)} placeholder="Pick or type the customer…" createLabel="Add the customer" />
        </Field>
        <Field label="Invoice #"><Input placeholder="e.g. INV-1065" value={f.nrFactura} onChange={e => set('nrFactura', 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="Amount, before sales tax" required><NumberInput placeholder="0.00" value={f.sumaNeta} onChange={e => set('sumaNeta', e.target.value)} /></Field>
        <Field label="Sales tax rate" hint="The rate where you sell. Charged to the customer on top, owed to the state. Not income."><RateField value={f.cotaTva} onChange={v => set('cotaTva', v)} /></Field>

        <div className="sm:col-span-2 grid grid-cols-2 gap-4 p-3.5 rounded-xl" style={{ background: '#F1FBD4' }}>
          <div><div className="text-[12px] text-muted">Sales tax</div><div className="text-[16px] font-700 num mt-0.5" style={{ color: 'var(--primary)' }}>{moneyUSD(tva)}</div></div>
          <div className="text-right"><div className="text-[12px] text-muted">Total</div><div className="text-[16px] font-700 num mt-0.5 text-ink">{moneyUSD(brut)}</div></div>
        </div>

        <Field label="Payment terms (days)"><NumberInput value={f.termenPlata} onChange={e => set('termenPlata', e.target.value)} /></Field>
        <Field label="Due date" hint="Invoice date + payment terms"><Input type="date" value={f.dataScadenta || ''} onChange={e => { setTouchedScad(true); set('dataScadenta', e.target.value); }} /></Field>
        <Field label="Note" className="sm:col-span-2"><Textarea rows={2} placeholder="What the invoice is for…" value={f.notes} onChange={e => set('notes', e.target.value)} /></Field>
        <div className="sm:col-span-2"><LockedStrip items={IN_LOCKED_FIELDS} /></div>
      </div>
    </Modal>
  );
}

/* A locked column: its header has a lock; each cell a blurred made-up value. */
function LockedHeader({ feature, children, className = '' }) {
  return (
    <th className={'text-left font-600 py-3 ' + className}>
      <button type="button" onClick={() => openPaid(feature)} className="inline-flex items-center gap-1 uppercase tracking-wide hover:text-ink" title="Part of the paid plan">{children}<LockMark size={11} /></button>
    </th>
  );
}
const _SAMPLE_JOB_NAMES = ['Westchase remodel', 'Katy ISD gym', 'Heights addition', 'Memorial office', 'Pearland roof'];
function LockedCell({ i, feature }) {
  return (
    <button type="button" onClick={() => openPaid(feature)} className="block w-full text-left" title="Part of the paid plan">
      <span aria-hidden="true" className="block text-[12.5px] text-muted truncate select-none" style={{ filter: 'blur(3.5px)' }}>{_SAMPLE_JOB_NAMES[i % _SAMPLE_JOB_NAMES.length]}</span>
    </button>
  );
}

function Incasari() {
  const db = useDB();
  // Filters, search and sort: kept while the page is open, empty after a reload. All the logic is in filters.jsx.
  const [fs, setFs] = useFilterState('incasari');
  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.incasari, fs, 'incasari');
  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="incasari" state={fs} setState={setFs} rows={db.incasari}
          searchPlaceholder="Search customer, invoice, amount…"
          onDownload={() => downloadFilteredCSV('incasari', rows, fs)} downloadCount={rows.length}
          right={<>
            <LockedButton feature="import" icon="upload">Import</LockedButton>
            <Button variant="primary" icon="plus" onClick={openAdd}>Add money in</Button>
          </>} />
      </Card>

      <Card className="overflow-hidden">
        <div className="overflow-x-auto scroll-area">
          <table className="w-full min-w-[1080px] border-collapse" style={{ tableLayout: 'fixed' }}>
            <colgroup><col style={{ width: '52px' }} /><col style={{ width: '104px' }} /><col style={{ width: '20%' }} /><col style={{ width: '13%' }} />{trade && <col style={{ width: '12%' }} />}<col style={{ width: '104px' }} /><col style={{ width: '104px' }} /><col style={{ width: '88px' }} /><col style={{ width: '112px' }} /><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="client" state={fs} setState={setFs}>Customer</SortHeader>
                <SortHeader className="px-3" sortKey="categorie" state={fs} setState={setFs}>Category</SortHeader>
                {trade && <LockedHeader feature="jobs" className="px-3">Job</LockedHeader>}
                <SortHeader className="px-3" sortKey="nrFactura" state={fs} setState={setFs}>Invoice #</SortHeader>
                <SortHeader className="px-3" sortKey="sumaNeta" state={fs} setState={setFs} align="right">Amount</SortHeader>
                <SortHeader className="px-3" sortKey="tva" state={fs} setState={setFs} align="right">Sales tax</SortHeader>
                <SortHeader className="px-3" sortKey="brut" state={fs} setState={setFs} align="right">Total</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 tva = vatOfRow(r);
                const flagged = r.needsReview || missingDueDate(r, 'in');
                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 => updateIncasare(r.id, { data: val })}>{fmtDate(r.data)}</EditCell></td>
                    <td className="py-1.5 px-3">
                      <EditCell type="pick" required value={r.client} options={namesOf('client')} onCreate={name => addName('client', name)} onSave={val => val && updateIncasare(r.id, { client: val })}>
                        <div className="flex items-center gap-2 min-w-0 w-full"><span className="text-[13px] font-medium text-ink truncate">{r.client}</span></div>
                      </EditCell>
                    </td>
                    <td className="py-1.5 px-3">
                      <EditCell type="pick" value={r.categorie || ''} options={DB.categoriiIn.map(c => c.name)} onCreate={name => addCategorieNamed(name, 'income')} emptyLabel="— No category —" onSave={val => updateIncasare(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-[12.5px] text-muted">—</span>}
                      </EditCell>
                    </td>
                    {trade && <td className="py-1.5 px-3"><LockedCell i={i} feature="jobs" /></td>}
                    <td className="py-1.5 px-3">
                      <EditCell value={r.nrFactura || ''} onSave={val => updateIncasare(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 => updateIncasare(r.id, { sumaNeta: val })}>
                        <span className="text-[13px] num text-ink font-medium whitespace-nowrap">{moneyUSD(r.sumaNeta)}</span>
                      </EditCell>
                    </td>
                    <td className="py-2.5 px-3 text-right text-[12.5px] num text-muted whitespace-nowrap">{tva ? moneyUSD(tva) : '—'}</td>
                    <td className="py-2.5 px-3 text-right whitespace-nowrap"><div className="text-[13px] num text-ink">{moneyUSD(r.sumaNeta + tva)}</div></td>
                    <td className="py-2.5 px-3"><InlineStatus value={r.status} options={STATUS_PICK} onChange={val => updateIncasare(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-600 text-ink">{moneyUSD(t.net)}</div></td>
              <td className="px-3 py-3.5 align-top text-right"><div className="text-[10.5px] uppercase tracking-wide text-muted">Sales tax</div><div className="num text-[13px] font-600 text-ink">{moneyUSD(t.tva)}</div></td>
              <td className="px-3 py-3.5 align-top text-right"><div className="text-[10.5px] uppercase tracking-wide text-muted">Total</div><div className="num text-[13px] font-700 text-ink">{moneyUSD(t.brut)}</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 + incasatEfectiv(r), 0))}</div></td>
              <td></td>
            </tr></tfoot>
          )}
          </table>
        </div>
        {rows.length === 0 && <EmptyState icon="in" title={hasFilters ? 'Nothing found' : 'No money in yet'} message={hasFilters ? 'Nothing matches the current filters. Try clearing them.' : 'Add your first invoice or payment received to start.'} action={hasFilters ? <Button variant="soft" icon="refresh" onClick={reset}>Clear filters</Button> : <Button variant="primary" icon="plus" onClick={openAdd}>Add money in</Button>} />}
      </Card>

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

function Totalcell({ label, value, strong }) {
  return (
    <div className="text-right">
      <div className="text-[11px] uppercase tracking-wide text-muted">{label}</div>
      <div className={`num ${strong ? 'text-[15px] font-700 text-ink' : 'text-[14px] font-600 text-ink'}`}>{value}</div>
    </div>
  );
}

Object.assign(window, { Incasari, IncasareForm, Totalcell, RateField, LockedHeader, LockedCell });
