import type { Table } from '@tanstack/angular-table';
import type { LabeledColumn } from '../../../components/data-table/types';

export interface TableExportAtom {
  exportCsv<T>(table: Table<T>, columns: LabeledColumn[], filename: string): void;
  exportXls<T>(table: Table<T>, columns: LabeledColumn[], filename: string): void;
}

/**
 * Atom: table export helpers. Single responsibility — generates CSV/XLS
 * blobs from the visible rows of a TanStack `Table<T>` and triggers a
 * browser download. Stateless — pure functions wrapped as an atom for
 * uniformity with the other table atoms.
 *
 * Exports the CURRENT page only. Full-dataset export is a separate concern
 * (typically requires a fetcher call, not a table operation).
 */
export function useTableExport(): TableExportAtom {
  return {
    exportCsv<T>(table: Table<T>, columns: LabeledColumn[], filename: string): void {
      const csv = generateCsv(table, columns);
      downloadFile(csv, `${filename}.csv`, 'text/csv');
    },
    exportXls<T>(table: Table<T>, columns: LabeledColumn[], filename: string): void {
      const csv = generateCsv(table, columns);
      downloadFile(csv, `${filename}.xls`, 'application/vnd.ms-excel');
    },
  };
}

function generateCsv<T>(table: Table<T>, columns: LabeledColumn[]): string {
  const rows = table.getRowModel().rows;
  const header = columns.map((c) => `"${c.label}"`).join(';');
  const body = rows.map((row) =>
    columns
      .map((c) => {
        const value = String(row.getValue(c.key) ?? '').replace(/"/g, '""');
        return `"${value}"`;
      })
      .join(';'),
  );
  return [header, ...body].join('\n');
}

function downloadFile(content: string, filename: string, mimeType: string): void {
  const bom = '﻿';
  const blob = new Blob([bom + content], { type: `${mimeType};charset=utf-8` });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  a.click();
  URL.revokeObjectURL(url);
}
