import { Component, Input, Output, EventEmitter, SimpleChanges, ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'app-pagination',
  templateUrl: './pagination.component.html',
  styleUrls: ['./pagination.component.scss']
})
export class PaginationComponent {
  @Input() totalItems = 0;
  @Input() pageSize = 10;
  currentPage = 1;
  @Output() pageChange = new EventEmitter<number>();
  @Output() pageSizeChange = new EventEmitter<number>();
  pageSizes: number[] = [10, 20, 50, 100];

  constructor(private cdr: ChangeDetectorRef) { }
  ngOnChanges() {
    this.changePage(1)
    this.cdr.detectChanges();


  }
  get totalPages(): number {
    return Math.ceil(this.totalItems / this.pageSize);
  }

  get visiblePages(): (number | string)[] {
    const total = this.totalPages;
    const current = this.currentPage;
    const pages: (number | string)[] = [];

    if (total <= 7) {
      return Array.from({ length: total }, (_, i) => i + 1);
    }
    pages.push(1);
    if (current > 3) pages.push('...');

    const middlePages = [current - 1, current, current + 1].filter(p => p > 1 && p < total);
    pages.push(...middlePages);

    if (current < total - 2) pages.push('...');
    pages.push(total);

    return pages;
  }

  changePage(newPage: any) {
    if (newPage >= 1 && newPage <= this.totalPages && newPage !== this.currentPage) {
      this.currentPage = newPage;
      this.pageChange.emit(this.currentPage);
    }
  }

  onPageSizeChange() {
    this.pageSizeChange.emit(this.pageSize);
  }

  getEndIndex(): number {
    return Math.min(this.currentPage * this.pageSize, this.totalItems);
  }
}
