// views/dupes.jsx — find and remove rows already in the ledger twice, which is
// what happens when an overlapping statement gets imported a second time.
function LedgerDupes({ banks, defaultBank }) {
  const s = useStore();
  const [bank, setBank] = React.useState(defaultBank || 'all');
  const [open, setOpen] = React.useState(true);
  const [done, setDone] = React.useState(null);

  const groups = React.useMemo(
    () => Store.findLedgerDuplicates(bank === 'all' ? {} : { bankAccountId: bank }),
    [s.transactions, bank]);

  const extras = groups.reduce((n, g) => n + g.extras.length, 0);
  const extraValue = groups.reduce((n, g) => n + g.extras.reduce((a, t) => a + (t.amount || 0), 0), 0);
  const bankName = id => ((s.bankAccounts || []).find(b => b.id === id) || {}).name || id;

  function removeGroup(g) {
    const n = Store.deleteTxs(g.extras.map(t => t.id));
    setDone({ n });
  }
  function removeAll() {
    if (!confirm(
      'Delete ' + extras + ' duplicate row' + (extras === 1 ? '' : 's') + ' across ' + groups.length + ' group' + (groups.length === 1 ? '' : 's') + '?\n\n' +
      'The first copy of each is kept, with its classification. Balances are recomputed.\n' +
      'A snapshot is taken first, so this is reversible from the Sync page.')) return;
    const ids = [];
    groups.forEach(g => g.extras.forEach(t => ids.push(t.id)));
    const n = Store.deleteTxs(ids);
    setDone({ n });
  }

  const bankFilter = (
    <FilterSelect label="Account" value={bank} options={[
      { value: 'all', label: 'All accounts' },
      ...(s.bankAccounts || []).map(b => ({ value: b.id, label: b.name + ' · ····' + (b.last4 || '----') })),
    ]} onChange={setBank} />
  );

  if (!groups.length) {
    return (
      <div className="vendor-tidy clean">
        <span>✓ {done ? done.n + ' duplicate row' + (done.n === 1 ? '' : 's') + ' removed — ' : ''}no duplicate rows in {bank === 'all' ? 'the ledger' : bankName(bank)}.</span>
        <div style={{ marginTop: 8 }}>{bankFilter}</div>
      </div>
    );
  }

  return (
    <div className="vendor-tidy">
      <div className="row" style={{ justifyContent: 'space-between', alignItems: 'center', gap: 16 }}>
        <div>
          <strong>{extras} row{extras === 1 ? '' : 's'} {extras === 1 ? 'is' : 'are'} in the ledger twice.</strong>
          <span className="muted" style={{ fontSize: 12, marginLeft: 8 }}>
            Same account, date, amount and description across {groups.length} group{groups.length === 1 ? '' : 's'} — {fmtINR(extraValue)} of phantom movement inflating your balances and your P&amp;L.
          </span>
        </div>
        <div className="row gap-2" style={{ alignItems: 'center' }}>
          {bankFilter}
          <button className="btn btn-sm btn-ghost" onClick={() => setOpen(o => !o)}>{open ? 'Hide' : 'Show'}</button>
          <button className="btn btn-sm" onClick={removeAll}>Remove all {extras}</button>
        </div>
      </div>

      {open && (
        <div className="vt-list">
          {groups.map(g => (
            <div className="vt-group" key={g.keep.id}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="dup-line">
                  <span className="num">{fmtDate(g.keep.date)}</span>
                  <span className="dup-part">{g.keep.particulars}</span>
                  <span className={'num ' + (g.keep.direction === 'credit' ? 't-credit' : 't-debit')}>
                    {g.keep.direction === 'credit' ? '+' : '−'}{fmtINR(g.keep.amount)}
                  </span>
                </div>
                <div className="muted" style={{ fontSize: 11, marginTop: 4 }}>
                  {bankName(g.keep.bankAccountId)} · {g.rows.length} copies · keeping <b>{g.keep.id}</b>
                  {g.keep.classified ? ' (classified' + (g.keep.category ? ' · ' + g.keep.category : '') + ')' : ' (unclassified)'}
                  {g.extras.some(t => t.classified) && <span className="dup-warn"> · a copy you are deleting was classified</span>}
                </div>
              </div>
              <button className="btn btn-sm" onClick={() => removeGroup(g)}>
                Delete {g.extras.length} extra{g.extras.length === 1 ? '' : 's'}
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { LedgerDupes });
