import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';
import { ButtonComponent } from '../button/button.component';
import { IconComponent } from '../icon/icon.component';

const SIBLING_COUNT = 1;
const ELLIPSIS = '…' as const;

@Component({
  selector: 'app-pagination',
  standalone: true,
  imports: [ButtonComponent, IconComponent],
  templateUrl: './pagination.component.html',
  styleUrl: './pagination.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class PaginationComponent {
  readonly currentPage = input.required<number>();
  readonly totalPages = input.required<number>();
  readonly previousLabel = input('Previous');
  readonly nextLabel = input('Next');

  readonly pageChange = output<number>();

  protected readonly pages = computed<(number | typeof ELLIPSIS)[]>(() => {
    const total = this.totalPages();
    const current = this.currentPage();
    const result: (number | typeof ELLIPSIS)[] = [];

    const rangeStart = Math.max(2, current - SIBLING_COUNT);
    const rangeEnd = Math.min(total - 1, current + SIBLING_COUNT);

    result.push(1);
    if (rangeStart > 2) {
      result.push(ELLIPSIS);
    }
    for (let page = rangeStart; page <= rangeEnd; page++) {
      result.push(page);
    }
    if (rangeEnd < total - 1) {
      result.push(ELLIPSIS);
    }
    if (total > 1) {
      result.push(total);
    }

    return result;
  });

  protected goTo(page: number): void {
    if (page === this.currentPage() || page < 1 || page > this.totalPages()) {
      return;
    }
    this.pageChange.emit(page);
  }

  protected isEllipsis(value: number | typeof ELLIPSIS): value is typeof ELLIPSIS {
    return value === ELLIPSIS;
  }
}
