import { ChangeDetectionStrategy, Component, input } from '@angular/core';
import { TranslocoDirective } from '@jsverse/transloco';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideDownload } from '@ng-icons/lucide';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmIconImports } from '@spartan-ng/helm/icon';
import { HlmPopoverImports } from '@spartan-ng/helm/popover';
import type { Table } from '@tanstack/angular-table';
import type { LabeledColumn } from '../types';

@Component({
  selector: 'au-table-export',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [NgIcon, TranslocoDirective, HlmButtonImports, HlmIconImports, HlmPopoverImports],
  providers: [provideIcons({ lucideDownload })],
  host: { class: 'block' },
  template: `
    <hlm-popover
      *transloco="let t"
      align="end"
    >
      <button
        hlmPopoverTrigger
        hlmBtn
        variant="outline"
        size="sm"
      >
        <ng-icon
          name="lucideDownload"
          class="sm:mr-1"
          hlm
          size="sm"
        />
        <span class="hidden sm:inline">{{ t('Export') }}</span>
      </button>
      <hlm-popover-content
        *hlmPopoverPortal
        class="w-44 p-2"
      >
        <button
          class="hover:bg-accent flex w-full items-center gap-2 rounded-md px-3 py-2 text-sm transition-colors"
          (click)="exportCSV()"
        >
          {{ t('DownloadCSV') }}
        </button>
        <button
          class="hover:bg-accent flex w-full items-center gap-2 rounded-md px-3 py-2 text-sm transition-colors"
          (click)="exportExcel()"
        >
          {{ t('DownloadExcel') }}
        </button>
      </hlm-popover-content>
    </hlm-popover>
  `,
})
export class TableExport<T> {
  readonly table = input.required<Table<T>>();
  readonly columns = input.required<LabeledColumn[]>();
  readonly filename = input('export');

  exportCSV() {
    this.downloadFile(this.generateCSV(), `${this.filename()}.csv`, 'text/csv');
  }

  exportExcel() {
    this.downloadFile(this.generateCSV(), `${this.filename()}.xls`, 'application/vnd.ms-excel');
  }

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

  private downloadFile(content: string, filename: string, mimeType: string) {
    const bom = '\uFEFF';
    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);
  }
}
