import { CommonModule } from '@angular/common';
import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';

@Component({
  selector: 'app-paginator',
  imports: [CommonModule],
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './paginator.html',
  styleUrl: './paginator.css',
})
export class Paginator {
  page = input(1);
  perPage = input(10);
  total = input(0);
  pageSizes = input([10, 20, 50]);

  pageChange = output<number>();
  perPageChange = output<number>();

  totalPages = computed(() => Math.max(1, Math.ceil(this.total() / this.perPage())));

  /** Pages visibles (avec ellipses) */
  visiblePages = computed(() => {
    const total = this.totalPages();
    const current = this.page();
    const delta = 2;
    const range: (number | string)[] = [];
    const left = Math.max(2, current - delta);
    const right = Math.min(total - 1, current + delta);

    range.push(1);
    if (left > 2) range.push('...');
    for (let i = left; i <= right; i++) range.push(i);
    if (right < total - 1) range.push('...');
    if (total > 1) range.push(total);
    return range;
  });

  /** Tableau complet des pages pour le sélecteur */
  totalPagesArray = computed(() => Array.from({ length: this.totalPages() }, (_, i) => i + 1));

  prev() {
    const newPage = this.page() - 1;
    if (newPage >= 1) this.pageChange.emit(newPage);
  }

  next() {
    const newPage = this.page() + 1;
    if (newPage <= this.totalPages()) this.pageChange.emit(newPage);
  }

  goToPage(p: number) {
    if (p >= 1 && p <= this.totalPages()) this.pageChange.emit(p);
  }

  handlePerPageChange(event: Event) {
    const value = (event.target as HTMLSelectElement).value;
    this.perPageChange.emit(parseInt(value, 10));
  }

  /** Quand on sélectionne une page depuis le select */
  selectPage(event: Event) {
    const pageNumber = parseInt((event.target as HTMLSelectElement).value, 10);
    if (!isNaN(pageNumber) && pageNumber >= 1 && pageNumber <= this.totalPages()) {
      this.pageChange.emit(pageNumber);
    }
  }
}
