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

type PaginatorAction = 'first' | 'previous' | 'next' | 'last';

@Component({
  selector: 'app-paginator',
  standalone: true,
  templateUrl: './paginator.component.html',
  styleUrl: './paginator.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class PaginatorComponent {
  readonly page = input.required<number>();
  readonly totalPages = input.required<number>();
  readonly disabled = input(false);

  readonly pageChange = output<number>();

  protected readonly displayPage = computed(() => {
    const totalPages = this.displayTotalPages();

    if (totalPages < 1) {
      return 0;
    }

    return Math.min(Math.max(this.page(), 1), totalPages);
  });

  protected readonly displayTotalPages = computed(() => Math.max(this.totalPages(), 0));

  protected readonly isNavigationDisabled = computed(() => {
    const page = this.page();
    const totalPages = this.totalPages();

    return (
      this.disabled() ||
      !Number.isInteger(page) ||
      !Number.isInteger(totalPages) ||
      totalPages <= 1 ||
      page < 1 ||
      page > totalPages
    );
  });

  protected readonly isFirstStepDisabled = computed(
    () => this.isNavigationDisabled() || this.displayPage() <= 1
  );

  protected readonly isLastStepDisabled = computed(
    () => this.isNavigationDisabled() || this.displayPage() >= this.displayTotalPages()
  );

  protected changePage(action: PaginatorAction): void {
    if (this.isNavigationDisabled()) {
      return;
    }

    const currentPage = this.displayPage();
    const totalPages = this.displayTotalPages();

    const nextPageByAction: Record<PaginatorAction, number> = {
      first: 1,
      previous: currentPage - 1,
      next: currentPage + 1,
      last: totalPages
    };

    const nextPage = nextPageByAction[action];

    if (nextPage === currentPage || nextPage < 1 || nextPage > totalPages) {
      return;
    }

    this.pageChange.emit(nextPage);
  }
}
