/* ============================================================
   P&L App (Lite) · Admin (from the US demo's)
   ------------------------------------------------------------
   - QuickBooks: one soft line, LOCKED (the paid plan reads it every night).
   - Lists and settings: Vendors, Customers, Categories (income, and expense as direct cost
     or overhead), How it works. Jobs and Vehicles are gone from here: their tabs are locked.
   - To review: rows missing something (a category, a due date on an unpaid row, a date far in
     the future). Worked out from the row; fixing the row takes it off the list.
   ============================================================ */
const REVIEW_PAGE = 8;

/* Connect QuickBooks: a paid-plan feature. */
function QuickBooksLine() {
  return (
    <button type="button" onClick={() => openPaid('quickbooks')} className="self-start inline-flex flex-wrap items-center gap-x-3 gap-y-1 text-[12.5px] text-muted hover:text-ink">
      <span className="inline-flex items-center gap-1.5 font-600"><LockMark size={13} />Connect QuickBooks</span>
      <span>and the automatic import are on the paid plan.</span>
      <span className="font-600" style={{ color: 'var(--primary)' }}>See how</span>
    </button>
  );
}

function Admin() {
  const db = useDB();
  const [del, setDel] = useState(null);       // queue row waiting for "are you sure?" (holds the record + _kind)
  const [panel, setPanel] = useState(null);   // which list is open in the centre window
  const [open, setOpen] = useState(null);     // queue row opened in the detail card
  const [reasons, setReasons] = useState([]); // reasons ticked in the queue filter (empty = all)
  const [all, setAll] = useState(false);      // show every row, not just the first 8

  // What needs a person: a missing category, a date far in the future, an unpaid row with no due date.
  // All worked out live from the row, never stored.
  const MISSING = 'Missing due date';
  const reasonsOf = r => {
    const out = [];
    String(r.needsReview ? (r.reviewReason || 'Needs a check') : '').split(';').map(s => s.trim()).filter(Boolean)
      .forEach(s => out.push(s.replace(/\s*\(.*\)\s*$/, '')));
    if (missingDueDate(r, r._kind)) out.push(MISSING);
    return out;
  };
  const queueAll = [
    ...db.incasari.map(r => ({ ...r, _kind: 'in' })),
    ...db.plati.map(r => ({ ...r, _kind: 'out' })),
  ].map(r => ({ ...r, _reasons: reasonsOf(r) })).filter(r => r._reasons.length > 0);
  const reasonCounts = {};
  queueAll.forEach(r => r._reasons.forEach(x => { reasonCounts[x] = (reasonCounts[x] || 0) + 1; }));
  const queue = queueAll.filter(r => reasons.length === 0 || r._reasons.some(x => reasons.includes(x)))
                        .sort((a, b) => b.data.localeCompare(a.data));
  const shown = all ? queue : queue.slice(0, REVIEW_PAGE);
  const toggleReason = x => { setAll(false); setReasons(p => p.includes(x) ? p.filter(y => y !== x) : [...p, x]); };

  return (
    <div className="flex flex-col gap-6">
      <QuickBooksLine />

      {/* Lists and settings: small buttons; each opens its manager in a wide centre window.
          To add one later: one entry in ADMIN_LISTS and one line in the panel switch below. */}
      <div>
        <h3 className="text-[13px] font-700 text-muted uppercase tracking-wide mb-3">Lists and settings</h3>
        <div className="flex flex-wrap gap-2.5">
          {ADMIN_LISTS(db).map(l => (
            <button key={l.key} onClick={() => setPanel(l.key)}
              className="inline-flex items-center gap-2.5 h-11 pl-3 pr-4 rounded-xl border border-line bg-surface hover:border-[#C9D9B8] hover:bg-[#F6F8F3] transition-colors">
              <span className="inline-flex items-center justify-center w-7 h-7 rounded-lg bg-[#F1FBD4] text-primary"><Icon name={l.icon} size={15} /></span>
              <span className="text-[13.5px] font-600 text-ink">{l.title}</span>
              {l.count != null && <span className="text-[12px] text-muted num">{l.count}</span>}
            </button>
          ))}
          {/* teammates: paid plan (Ana, 17 Nov 2026: the free plan is one login per company) */}
          <button type="button" onClick={() => openPaid('team')} title="Part of the paid plan"
            className="inline-flex items-center gap-2.5 h-11 pl-3 pr-4 rounded-xl border border-dashed border-line bg-surface hover:bg-[#F6F8F3] transition-colors">
            <span className="inline-flex items-center justify-center w-7 h-7 rounded-lg bg-[#F6F8F3] text-muted"><Icon name="user" size={15} /></span>
            <span className="text-[13.5px] font-600 text-muted">Add a teammate</span>
            <LockMark size={13} />
          </button>
        </div>
      </div>

      {/* Review queue */}
      <Card className="overflow-hidden">
        <div className="flex items-center justify-between gap-4 px-6 pt-5 pb-4 border-b border-line">
          <div className="flex items-center gap-3">
            <span className="inline-flex items-center justify-center w-9 h-9 rounded-xl shrink-0" style={{ background: '#FBEAE8', color: 'var(--neg)' }}><Icon name="alert" size={19} /></span>
            <div>
              <h3 className="text-[15.5px] font-700 text-ink font-display">To review</h3>
              <p className="text-[12.5px] text-muted mt-0.5">Rows missing something. Open one, fill in what is missing, and it leaves this list.</p>
            </div>
          </div>
          {queueAll.length > 0 && <Badge tone="neg">{queueAll.length}</Badge>}
        </div>
        {queueAll.length > 0 && (
          <div className="flex flex-wrap items-center gap-1.5 px-6 py-3 border-b border-line bg-[#F6F8F3]">
            <span className="text-[12px] text-muted mr-1">Reason:</span>
            {Object.keys(reasonCounts).sort((a, b) => reasonCounts[b] - reasonCounts[a]).map(x => {
              const on = reasons.includes(x);
              return (
                <button key={x} onClick={() => toggleReason(x)}
                  className={'inline-flex items-center gap-1.5 h-7 px-2.5 rounded-full text-[12px] border transition-colors ' + (on ? 'bg-primary text-white border-primary' : 'bg-surface text-ink border-line hover:border-[#C9D9B8]')}>
                  {x}<span className={'num ' + (on ? 'text-white/80' : 'text-muted')}>{reasonCounts[x]}</span>
                </button>
              );
            })}
            {reasons.length > 0 && <button onClick={() => setReasons([])} className="text-[12px] text-muted hover:text-primary ml-1">Show all reasons</button>}
            {reasonCounts[MISSING] > 0 && (
              <p className="w-full text-[12px] text-muted mt-1.5">
                <b className="text-ink font-600">{MISSING}</b> = not paid yet (Unpaid) and no due date. Paid rows do not need one. Fill in the date, or mark it paid, and it leaves this list.
              </p>
            )}
          </div>
        )}

        {queue.length === 0 ? (
          <EmptyState icon="check" title="All checked" message="Nothing needs a look. A row missing a category or a due date will show here." />
        ) : (
          <div className="divide-y divide-line">
            {shown.map(r => (
              <div key={r._kind + r.id} className="flex flex-wrap items-center gap-x-5 gap-y-2.5 px-6 py-3.5 hover:bg-[#F6F8F3] transition-colors">
                <span className="inline-flex items-center justify-center w-9 h-9 rounded-xl shrink-0"
                  style={{ background: r._kind === 'in' ? '#E6F4EA' : '#F1FBD4', color: r._kind === 'in' ? 'var(--pos)' : 'var(--primary)' }}>
                  <Icon name={r._kind === 'in' ? 'in' : 'out'} size={18} />
                </span>
                <div className="min-w-[180px] flex-1">
                  <div className="flex items-center gap-2">
                    <span className="text-[13.5px] font-600 text-ink">{r._kind === 'in' ? r.client : r.furnizor}</span>
                  </div>
                  <div className="text-[12px] text-muted num mt-0.5">{fmtDate(r.data)} · {r.categorie || 'no category'}</div>
                </div>
                <div className="ml-auto flex flex-wrap items-center justify-end gap-x-4 gap-y-2">
                  <div className="flex flex-wrap gap-1 justify-end max-w-[280px]">{r._reasons.map(x => <span key={x} className="inline-flex items-center px-2 h-6 rounded-full text-[11.5px] whitespace-nowrap" style={{ background: x === MISSING ? '#FFF4DD' : '#FBEAE8', color: x === MISSING ? '#9A6B12' : 'var(--neg)' }}>{x}</span>)}</div>
                  <span className="text-[14px] font-700 num text-ink w-[110px] text-right">{moneyUSD(brutOfRow(r))}</span>
                  <div className="flex items-center gap-2">
                    <Button variant="outline" size="sm" icon="arrowRight" onClick={() => setOpen(r)}>Open</Button>
                    <Button variant="danger" size="sm" icon="trash" onClick={() => setDel(r)}>Delete</Button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
        {queue.length > REVIEW_PAGE && (
          <div className="px-6 py-3 border-t border-line text-[12.5px] text-muted flex items-center gap-2">
            Showing {shown.length} of {queue.length}
            <button onClick={() => setAll(a => !a)} className="font-600 hover:underline" style={{ color: 'var(--primary)' }}>{all ? 'Show fewer' : 'Show all'}</button>
          </div>
        )}
      </Card>

      {(() => { const cur = ADMIN_LISTS(db).find(l => l.key === panel); return (
        <Modal open={!!cur} onClose={() => setPanel(null)} width={760} icon={cur && cur.icon} title={cur ? cur.title : ''} subtitle={cur ? cur.sub : ''}>
          {panel === 'furnizori' && <NameManager kind="furnizor" />}
          {panel === 'clienti' && <NameManager kind="client" />}
          {panel === 'categorii' && <CategoriiManager />}
          {panel === 'ghid' && <HowItWorks />}
        </Modal>); })()}


      <TransactionDetail record={open} kind={open ? open._kind : 'out'} onClose={() => setOpen(null)} onDelete={r => { setOpen(null); setDel(r); }} />

      <ConfirmDialog open={!!del} onClose={() => setDel(null)}
        onConfirm={() => del._kind === 'in' ? deleteIncasare(del.id) : deletePlata(del.id)}
        title="Delete this row?" confirmLabel="Delete for good"
        message={del
          ? `${del._kind === 'in' ? 'The money in from ' + del.client : 'The bill from ' + del.furnizor} (${moneyUSD(del.sumaNeta)}) will be deleted for good.`
          : ''} />
    </div>
  );
}

/* The buttons on the Admin page (one per list). */
const ADMIN_LISTS = db => [
  { key: 'furnizori', title: 'Vendors', icon: 'out', count: db.furnizori.length, sub: 'One official spelling per vendor' },
  { key: 'clienti', title: 'Customers', icon: 'in', count: db.clienti.length, sub: 'One official spelling per customer' },
  { key: 'categorii', title: 'Categories', icon: 'tag', count: db.categorii.length + db.categoriiIn.length, sub: 'Income categories, and expense categories as a direct cost or an overhead: gross profit is built on this' },
  { key: 'ghid', title: 'How it works', icon: 'sparkles', sub: 'The app in plain English' },
];

/* ---------- Categories: income, and expense as direct cost / overhead ----------
   A category in use cannot be deleted (the database refuses it too): rename it, or move its rows first. */
function CategoriiManager() {
  const db = useDB();
  const [name, setName] = useState('');
  const [type, setType] = useState('job');          // 'job' = direct cost (the demo's name), 'overhead', or 'income'
  const [editId, setEditId] = useState(null); const [eVal, setEVal] = useState('');
  const [del, setDel] = useState(null);
  const [blocked, setBlocked] = useState(null);

  const add = () => { if (name.trim()) { type === 'income' ? addCategorie(name.trim(), null, 'income') : addCategorie(name.trim(), type, 'expense'); setName(''); } };
  const saveEdit = () => { if (eVal.trim()) renameCategorie(editId, eVal.trim()); setEditId(null); };
  const Switch = ({ value, onPick, withIncome }) => (
    <div className="inline-flex rounded-lg border border-line overflow-hidden text-[12px] shrink-0">
      {withIncome && <button type="button" className={'px-2.5 h-7 ' + (value === 'income' ? 'bg-primary text-white' : 'text-ink hover:bg-[#F6F8F3]')} onClick={() => onPick('income')}>Income</button>}
      <button type="button" className={'px-2.5 h-7 ' + (value === 'job' ? 'bg-primary text-white' : 'text-ink hover:bg-[#F6F8F3]')} onClick={() => onPick('job')}>Direct cost</button>
      <button type="button" className={'px-2.5 h-7 ' + (value === 'overhead' ? 'bg-primary text-white' : 'text-ink hover:bg-[#F6F8F3]')} onClick={() => onPick('overhead')}>Overhead</button>
    </div>
  );
  const byName = (a, b) => a.name.localeCompare(b.name);
  const groups = [
    { title: 'Income', list: db.categoriiIn.slice().sort(byName), income: true },
    { title: 'Direct costs', note: 'The cost of doing the work. Revenue minus these = gross profit.', list: db.categorii.filter(c => (c.costType || 'job') === 'job').sort(byName) },
    { title: 'Overheads', note: 'Running the business, whatever you sell. Gross profit minus these = net income.', list: db.categorii.filter(c => c.costType === 'overhead').sort(byName) },
  ];
  const Row = ({ c, income }) => {
    const used = countByCategoryId(c.id);
    return (
      <div className="flex items-center gap-2 px-3 min-h-[48px] py-1.5 rounded-xl border border-line">
        {editId === c.id ? (
          <><Input autoFocus value={eVal} onChange={e => setEVal(e.target.value)} onKeyDown={e => e.key === 'Enter' && saveEdit()} className="h-8" /><IconButton icon="check" tone="pos" title="Save" onClick={saveEdit} /><IconButton icon="x" title="Cancel" onClick={() => setEditId(null)} /></>
        ) : (
          <>
            <span className="text-[12.5px] font-medium text-ink flex-1 min-w-0 break-words">{c.name}</span>
            <span className="text-[11px] text-muted num shrink-0 w-[56px] text-right">{used} {plural(used, 'row')}</span>
            {!income && <Switch value={c.costType || 'job'} onPick={t => t !== (c.costType || 'job') && setCategoryType(c.id, t)} />}
            <div className="flex gap-0.5"><IconButton icon="edit" size={15} title="Rename" onClick={() => { setEditId(c.id); setEVal(c.name); }} /><IconButton icon="trash" size={15} tone="neg" title="Delete" onClick={() => used ? setBlocked({ c, used }) : setDel(c)} /></div>
          </>
        )}
      </div>
    );
  };

  return (
    <div>
      <div className="flex flex-wrap gap-2 mb-4 items-center">
        <Input placeholder="New category…" value={name} onChange={e => setName(e.target.value)} onKeyDown={e => e.key === 'Enter' && add()} className="h-9 flex-1 min-w-[180px]" />
        <Switch value={type} onPick={setType} withIncome />
        <Button variant="primary" size="sm" icon="plus" onClick={add} className="shrink-0">Add</Button>
      </div>
      {groups.map(g => (
        <div key={g.title} className="mb-4">
          <div className="text-[12px] font-700 text-muted uppercase tracking-wide">{g.title}</div>
          {g.note && <div className="text-[12px] text-muted mb-1.5">{g.note}</div>}
          <div className="flex flex-col gap-1.5 mt-1.5">
            {g.list.map(c => <Row key={c.id} c={c} income={g.income} />)}
            {g.list.length === 0 && <div className="text-[12.5px] text-muted px-1">None yet.</div>}
          </div>
        </div>
      ))}
      <ConfirmDialog open={!!del} onClose={() => setDel(null)} onConfirm={() => deleteCategorie(del.id)}
        title="Delete the category?" confirmLabel="Delete"
        message={del ? `No row uses "${del.name}", so nothing else changes.` : ''} />
      <ConfirmDialog open={!!blocked} onClose={() => setBlocked(null)} danger={false} confirmLabel="OK" cancelLabel="Close" onConfirm={() => {}}
        title="This category is in use"
        message={blocked ? `${blocked.used} ${plural(blocked.used, 'row uses', 'rows use')} "${blocked.c.name}". Rename it instead, or give ${plural(blocked.used, 'that row', 'those rows')} another category first.` : ''} />
    </div>
  );
}

/* ---------- shared bits ---------- */
function DictHeader({ icon, title, sub }) {
  return (
    <div className="flex items-center gap-3 mb-4">
      <span className="inline-flex items-center justify-center w-9 h-9 rounded-xl bg-[#F1FBD4] text-primary shrink-0"><Icon name={icon} size={18} /></span>
      <div><h3 className="text-[14.5px] font-700 text-ink font-display">{title}</h3><p className="text-[11.5px] text-muted">{sub}</p></div>
    </div>
  );
}
function DictToggle({ show, setShow, label }) {
  return (
    <button onClick={() => setShow(s => !s)} className="flex items-center gap-1.5 text-[12px] text-muted hover:text-primary transition-colors">
      <Icon name={show ? 'eyeOff' : 'eye'} size={14} /> {label}
    </button>
  );
}

Object.assign(window, { Admin, ADMIN_LISTS });
