/* ============================================================
   P&L App (Lite) · the card that opens a row (from the US demo's)
   ------------------------------------------------------------
   Click Open on any money in / money out row (or a row in a figure's list) to see every
   detail and change it. Changes are a DRAFT until Save is pressed; closing with unsaved
   changes asks first. (A cell edited straight in the table still saves at once.)

   Paid-plan parts of the demo's card (the document, part payments, job, split, payment
   method, date paid, approved by, truck) show here as locked lines.
   ============================================================ */

/* One line in the card: a label and a value you can click to edit. */
function PropRow({ label, children, hint }) {
  return (
    <div className="grid grid-cols-[112px_1fr] sm:grid-cols-[128px_1fr] items-start gap-3 py-1.5">
      <span className="text-[12.5px] text-muted pt-[7px]">{label}</span>
      <div className="min-w-0">{children}{hint}</div>
    </div>
  );
}

function TransactionDetail({ record, kind, onClose, onDelete }) {
  // The parent stores a snapshot of the record; every reload replaces the rows with fresh objects,
  // so look the live row up by id (falls back to the snapshot if it was deleted).
  const db = useDB();
  const isIn = kind === 'in';
  const live = record ? (isIn ? db.incasari : db.plati).find(x => x.id === record.id) : null;
  const base = live || record;
  const [draft, setDraft] = React.useState({});
  const [askClose, setAskClose] = React.useState(false);
  React.useEffect(() => { setDraft({}); setAskClose(false); }, [record && record.id]);
  const r = base ? { ...base, ...draft } : null;
  const changed = base ? Object.keys(draft).filter(k => draft[k] !== base[k]) : [];
  const dirty = changed.length > 0;
  if (!r) return null;
  const upd = patch => setDraft(d => ({ ...d, ...patch }));
  const save = async () => {
    const patch = {}; changed.forEach(k => { patch[k] = draft[k]; });
    await (isIn ? updateIncasare : updatePlata)(base.id, patch);
    setDraft({}); onClose();
  };
  const requestClose = () => (dirty ? setAskClose(true) : onClose());
  const tva = vatOfRow(r);
  const brut = r.sumaNeta + tva;
  const needDue = missingDueDate(r, kind);
  // the status shown follows the draft: picking Unpaid on a row past its due date shows Overdue
  const shownStatus = 'status' in draft ? statusOf(draft.status === 'Paid', r.dataScadenta) : r.status;
  const cats = (isIn ? DB.categoriiIn : DB.categorii).map(c => c.name);

  return (
    <>
    <Modal open={!!record} onClose={requestClose} width={760} icon={isIn ? 'in' : 'out'}
      title={isIn ? 'Money in' : 'Money out'}
      subtitle={`${(isIn ? r.client : r.furnizor) || '—'} · ${fmtDate(r.data)} · click a value to change it, then Save`}
      footer={<>
        {onDelete && <Button variant="danger" size="sm" icon="trash" className="mr-auto" onClick={() => onDelete(r)}>Delete</Button>}
        <Button variant="ghost" onClick={requestClose}>Close</Button>
        <Button variant={dirty ? 'primary' : 'outline'} icon="check" onClick={dirty ? save : onClose} title={dirty ? 'Save the changes' : 'Nothing to save'}>Save</Button>
      </>}>

      {r.needsReview && (
        <div className="flex items-center gap-3 px-4 py-3 rounded-xl mb-3" style={{ background: '#FDF1F0' }}>
          <Icon name="alert" size={17} className="shrink-0" />
          <span className="flex-1 text-[12.5px] text-ink">{r.reviewReason} · fix it below and it leaves To review.</span>
        </div>
      )}

      <div className="rounded-xl border border-line px-4 py-2">
        <PropRow label="Date"><EditCell type="date" required value={r.data} onSave={v => upd({ data: v })}>{fmtDate(r.data)}</EditCell></PropRow>
        <PropRow label={isIn ? 'Customer' : 'Vendor'}>
          <EditCell type="pick" required value={isIn ? r.client : r.furnizor} options={namesOf(isIn ? 'client' : 'furnizor')}
                    onCreate={name => addName(isIn ? 'client' : 'furnizor', name)} onSave={v => v && upd(isIn ? { client: v } : { furnizor: v })} />
        </PropRow>
        <PropRow label="Category" hint={!isIn && r.categorie ? <div className="text-[11.5px] text-muted mt-0.5 px-1.5">{catTypeOf(r.categorie) === 'overhead' ? 'An overhead' : 'A direct cost'}</div> : null}>
          <EditCell type="pick" required={!isIn} value={r.categorie || ''} options={cats} emptyLabel={isIn ? '— No category —' : undefined}
                    onCreate={name => addCategorieNamed(name, isIn ? 'income' : 'expense')} onSave={v => (isIn || v) && upd({ categorie: v || '' })}>
            {r.categorie || <span className="text-[#9AA298]">Pick a category…</span>}
          </EditCell>
        </PropRow>
        <PropRow label={isIn ? 'Invoice #' : 'Bill #'}><EditCell value={r.nrFactura} onSave={v => upd({ nrFactura: v })} /></PropRow>
        <PropRow label="Note"><EditCell value={r.notes || ''} onSave={v => upd({ notes: v || null })}>{r.notes ? <span className="whitespace-pre-wrap">{r.notes}</span> : <span className="text-[#9AA298]">Add a note…</span>}</EditCell></PropRow>
      </div>

      <div className="rounded-xl border border-line px-4 py-2 mt-3">
        {isIn ? (<>
          <PropRow label="Amount"><EditCell type="number" value={r.sumaNeta} onSave={v => upd(vatEditPatch(r, 'net', v))}><span className="num">{moneyUSD(r.sumaNeta)}</span></EditCell></PropRow>
          <PropRow label="Sales tax rate">
            <EditCell type="number" value={r.cotaTva} onSave={v => v !== '' && v != null && Number(v) >= 0 && upd({ cotaTva: Number(v) })}>{r.cotaTva}%</EditCell>
          </PropRow>
          <PropRow label="Sales tax" hint={<div className="text-[11.5px] text-muted mt-0.5 px-1.5">Charged to the customer and owed to the state. Not income.</div>}><span className="text-[13px] num text-ink block py-1">{moneyUSD(tva)}</span></PropRow>
          <PropRow label="Total"><EditCell type="number" value={Math.round(brut * 100) / 100} onSave={v => upd(vatEditPatch(r, 'gross', v))}><span className="num font-700">{moneyUSD(brut)}</span></EditCell></PropRow>
        </>) : (
          <PropRow label="Amount" hint={<div className="text-[11.5px] text-muted mt-0.5 px-1.5">The full amount paid. Sales tax on a bill is part of the cost.</div>}>
            <EditCell type="number" value={r.sumaNeta} onSave={v => upd({ sumaNeta: Math.round(v * 100) / 100 })}><span className="num font-700">{moneyUSD(r.sumaNeta)}</span></EditCell>
          </PropRow>
        )}
      </div>

      <div className="rounded-xl border border-line px-4 py-2 mt-3">
        <PropRow label="Status" hint={<div className="text-[11.5px] text-muted mt-0.5 px-1.5">Overdue shows by itself once the due date has passed.</div>}>
          <div className="py-1"><InlineStatus value={shownStatus} options={STATUS_PICK} onChange={v => upd({ status: v })} /></div>
        </PropRow>
        <PropRow label="Due date"
          hint={needDue && <div className="text-[11.5px] mt-0.5 px-1.5" style={{ color: 'var(--neg)' }}>Not paid and no due date: fill it in.</div>}>
          <EditCell type="date" value={r.dataScadenta || ''} onSave={v => upd({ dataScadenta: v || null })}
                    className={needDue ? 'ring-1 ring-[#E8B4AE]' : ''}>{r.dataScadenta ? fmtDate(r.dataScadenta) : <span className="text-[#9AA298]">Pick a date…</span>}</EditCell>
        </PropRow>
        {isIn && (
          <PropRow label="Payment terms" hint={<div className="text-[11.5px] text-muted mt-0.5 px-1.5">Change it and the due date follows (invoice date + terms).</div>}>
            <EditCell type="number" value={r.termenPlata == null ? '' : r.termenPlata}
                      onSave={v => { if (v === '' || v == null) return; upd({ termenPlata: Number(v), dataScadenta: addDays(r.data, Number(v)) }); }}>
              {r.termenPlata != null ? 'Net ' + r.termenPlata + ' days' : <span className="text-[#9AA298]">Choose…</span>}
            </EditCell>
          </PropRow>
        )}
      </div>

      <div className="flex flex-col gap-2 mt-3">
        <LockedLine feature="document" label="The invoice or receipt, kept with the row" />
        <LockedLine feature="parts" label="Part payments" />
        {isIn && showTrade() && <LockedLine feature="retainage" label="Retainage held on this invoice" />}
        <LockedStrip items={isIn ? IN_LOCKED_FIELDS : OUT_LOCKED_FIELDS} />
      </div>
    </Modal>
    <ConfirmDialog open={askClose} onClose={() => setAskClose(false)} danger confirmLabel="Close without saving" cancelLabel="Keep editing"
      title="You have unsaved changes" message="Close now and the changes made in this window are lost. Press Save to keep them."
      onConfirm={() => { setDraft({}); setAskClose(false); onClose(); }} />
    </>
  );
}

/* Kept for the shared screens that still call them; Lite has no splits, so they are never reached with one. */
function splitText(split) { return (split || []).map(p => p.job || 'No job').join(' · '); }
function splitCategoryText(row) { return row.categorie || ''; }

Object.assign(window, { TransactionDetail, PropRow, splitText, splitCategoryText });
