import { CommonModule } from '@angular/common';
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { Router } from '@angular/router';
import { DataTable, TableColumn } from '@shared/components/data-table/data-table';
import { ZardButtonComponent } from '@shared/components/button/button.component';
import { ZardPaginationModule } from '@shared/components/pagination/pagination.module';
import { ListParams, PagedResult } from '@shared/paging/paging';
import { Gain } from 'src/app/core/services/gain';
import { ResultatCagnotte } from 'src/app/core/interfaces/gain';

@Component({
  standalone: true,
  selector: 'app-gains',
  templateUrl: './gains.html',
  styleUrl: './gains.css',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [CommonModule, DataTable, ZardButtonComponent, ZardPaginationModule],
})
export class Gains {
  rows = signal<ResultatCagnotte[]>([]);
  loading = signal(false);
  // Pagination
  page = signal<number>(1);
  perPage = signal<number>(10);
  totalPages = signal<number>(1);
  totalElements = signal<number>(0);

  cols: TableColumn<ResultatCagnotte>[] = [
    { key: 'course.nom', label: 'Course' , cell: (r) => r.course?.nom ?? '—'},
    { key: 'montantCagnotte', label: 'Montant cagnotte', cell: (r) => `${r.montantCagnotte.toLocaleString('fr-FR')} CFA` },
    { key: 'montantARembourser', label: 'Montant à rembourser', cell: (r) => `${r.montantARembourser.toLocaleString('fr-FR')} CFA` },
    { key: 'dateCalcul', label: 'Date calcul', cell: (r) => r.dateCalcul ?? '—' },
  ];

  constructor(private gainService: Gain, private router: Router) {
    this.fetchPage();
  }

  fetchPage(params?: Partial<ListParams>) {
    this.loading.set(true);
    const p: ListParams = { page: this.page(), size: this.perPage(), ...(params || {}) };
    this.gainService.list(p).subscribe({
      next: (res: PagedResult<ResultatCagnotte>) => {
        this.rows.set(res.content || []);
        this.totalPages.set(res.totalPages ?? 1);
        this.totalElements.set(res.totalElements ?? (res.content?.length ?? 0));
        if ((res as any).pageable?.pageNumber) this.page.set((res as any).pageable.pageNumber);
        this.loading.set(false);
      },
      error: (err) => {
        console.error('Error fetching gains:', err);
        this.rows.set([]);
        this.loading.set(false);
      }
    });
  }

  onPageChange(next: number) {
    this.page.set(next);
    this.fetchPage();
  }

  onPerPageChange(size: number) {
    this.perPage.set(size);
    this.page.set(1);
    this.fetchPage();
  }

  // Template-friendly wrapper to safely parse the select event value
  onPerPageChangeEvent(e: Event) {
    const v = (e.target as HTMLSelectElement)?.value;
    const size = Number(v) || 10;
    this.onPerPageChange(size);
  }

  openReport(row: ResultatCagnotte) {
    try {
      // Navigate to detail page
      this.router.navigate(['/gains', String(row.course.id)]);
    } catch (err) {
      console.error('Failed to open gain details for', row, err);
    }
  }
}
