/* AAU CRM — reusable DataTable (IndexTable pattern) */

function DataTable({ columns, rows, getId, searchKeys, selectable, bulkActions, onRowClick, toolbar, exportName = 'export', pageSize = 8, rowClass }) {
  const [q, setQ] = useState('');
  const [sort, setSort] = useState(null); // {key, dir}
  const [sel, setSel] = useState([]);
  const [page, setPage] = useState(0);
  const [cols, setCols] = useState(columns.map(c => c.key));
  const [colMenu, setColMenu] = useState(false);

  const visCols = columns.filter(c => cols.includes(c.key));
  let data = rows;
  if (q && searchKeys) data = data.filter(r => searchKeys.some(k => String(r[k] ?? '').toLowerCase().includes(q.toLowerCase())));
  if (sort) data = [...data].sort((a, b) => { const av = a[sort.key], bv = b[sort.key]; const r = av > bv ? 1 : av < bv ? -1 : 0; return sort.dir === 'asc' ? r : -r; });
  const pages = Math.max(1, Math.ceil(data.length / pageSize));
  const pageData = data.slice(page * pageSize, page * pageSize + pageSize);

  const toggleSel = id => setSel(s => s.includes(id) ? s.filter(x => x !== id) : [...s, id]);
  const allSel = pageData.length > 0 && pageData.every(r => sel.includes(getId(r)));
  const toggleAll = () => setSel(allSel ? sel.filter(id => !pageData.some(r => getId(r) === id)) : [...new Set([...sel, ...pageData.map(getId)])]);

  function exportCSV() {
    const head = visCols.map(c => c.label).join(',');
    const lines = data.map(r => visCols.map(c => '"' + String(c.csv ? c.csv(r) : r[c.key] ?? '').replace(/"/g, '""') + '"').join(','));
    const blob = new Blob(['\uFEFF' + head + '\n' + lines.join('\n')], { type: 'text/csv;charset=utf-8' });
    const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = exportName + '.csv'; a.click();
  }
  function setSortKey(k) { setSort(s => s && s.key === k ? { key: k, dir: s.dir === 'asc' ? 'desc' : 'asc' } : { key: k, dir: 'asc' }); }

  return (
    <div className="card" style={{ overflow: 'visible' }}>
      <div className="tbl-toolbar">
        {searchKeys && <div style={{ width: 240 }}><Input icon="search" placeholder="Tìm kiếm…" value={q} onChange={v => { setQ(v); setPage(0); }} /></div>}
        {toolbar}
        <div className="mla row aic g8" style={{ position: 'relative' }}>
          <Button size="sm" icon="columns" onClick={() => setColMenu(!colMenu)}>Cột</Button>
          {colMenu && (
            <div style={{ position: 'absolute', top: '110%', right: 70, zIndex: 20, background: '#fff', borderRadius: 10, boxShadow: 'var(--p-shadow-popover)', padding: 8, width: 200 }}>
              {columns.map(c => <div key={c.key} className="row aic g8" style={{ padding: '5px 6px', cursor: 'pointer' }} onClick={() => setCols(cs => cs.includes(c.key) ? cs.filter(x => x !== c.key) : [...cs, c.key])}><Checkbox on={cols.includes(c.key)} onChange={() => {}} /><span className="t12">{c.label}</span></div>)}
            </div>
          )}
          <Button size="sm" icon="download" onClick={exportCSV}>CSV</Button>
        </div>
      </div>
      {selectable && sel.length > 0 && (
        <div className="bulkbar">
          <span className="t13 fw6">{sel.length} đã chọn</span>
          <div className="row g6 mla">
            {(bulkActions || []).map((b, i) => <Button key={i} size="sm" icon={b.icon} onClick={() => b.onClick(sel)}>{b.label}</Button>)}
            <Button size="sm" onClick={() => setSel([])}>Bỏ chọn</Button>
          </div>
        </div>
      )}
      <div className="tbl-wrap">
        <table className="tbl">
          <thead><tr>
            {selectable && <th style={{ width: 36 }}><Checkbox on={allSel} onChange={toggleAll} /></th>}
            {visCols.map(c => <th key={c.key} className={c.num ? 'num' : ''} style={c.width ? { width: c.width } : null}>{c.sortable !== false ? <span className="th-sort" onClick={() => setSortKey(c.key)}>{c.label}{sort && sort.key === c.key && <Icon name={sort.dir === 'asc' ? 'arrowUp' : 'arrowDown'} size={12} />}</span> : c.label}</th>)}
          </tr></thead>
          <tbody>
            {pageData.map(r => { const id = getId(r); return (
              <tr key={id} className={(onRowClick ? 'clickable ' : '') + (sel.includes(id) ? 'sel ' : '') + (rowClass ? rowClass(r) : '')} onClick={onRowClick ? () => onRowClick(r) : undefined}>
                {selectable && <td onClick={e => { e.stopPropagation(); toggleSel(id); }}><Checkbox on={sel.includes(id)} onChange={() => {}} /></td>}
                {visCols.map(c => <td key={c.key} className={c.num ? 'num' : ''}>{c.render ? c.render(r) : r[c.key]}</td>)}
              </tr>
            ); })}
            {pageData.length === 0 && <tr><td colSpan={visCols.length + (selectable ? 1 : 0)}><EmptyState title="Không có dữ liệu" desc="Thử đổi bộ lọc hoặc từ khóa tìm kiếm." /></td></tr>}
          </tbody>
        </table>
      </div>
      <div className="pagination">
        <span>{data.length} kết quả · trang {page + 1}/{pages}</span>
        <Button size="sm" icon="chevronLeft" onClick={() => setPage(p => Math.max(0, p - 1))} disabled={page === 0} />
        <Button size="sm" icon="chevronRight" onClick={() => setPage(p => Math.min(pages - 1, p + 1))} disabled={page >= pages - 1} />
      </div>
    </div>
  );
}
window.DataTable = DataTable;
