import { AsyncPipe, NgForOf, NgIf } from '@angular/common';
import { AfterViewInit, Component, inject, Input } from '@angular/core';
import { List } from '@iqser/common-ui/lib/utils';
import { ViewedPage } from '@red/domain';
import { ViewedPagesMapService } from '@services/files/viewed-pages-map.service';
import scrollIntoView from 'scroll-into-view-if-needed';
import { PdfViewer } from '../../../pdf-viewer/services/pdf-viewer.service';
import { AnnotationsListingService } from '../../services/annotations-listing.service';
import { FilePreviewStateService } from '../../services/file-preview-state.service';
import { MultiSelectService } from '../../services/multi-select.service';
import { PageIndicatorComponent } from '../page-indicator/page-indicator.component';

@Component({
    selector: 'redaction-pages',
    templateUrl: './pages.component.html',
    styleUrls: ['./pages.component.scss'],
    standalone: true,
    imports: [PageIndicatorComponent, AsyncPipe, NgForOf, NgIf],
})
export class PagesComponent implements AfterViewInit {
    readonly #state = inject(FilePreviewStateService);
    readonly #multiSelectService = inject(MultiSelectService);
    readonly #listingService = inject(AnnotationsListingService);
    protected readonly _pdf = inject(PdfViewer);
    @Input({ required: true }) pages: List<number>;
    readonly viewedPages$ = inject(ViewedPagesMapService).get$(this.#state.fileId);

    ngAfterViewInit() {
        setTimeout(() => {
            this.scrollToLastViewedPage();
        }, 100);
    }

    // TODO: looks like this is not working
    scrollToLastViewedPage() {
        const currentPdfPage = this._pdf.currentPage();
        scrollIntoView(document.getElementById(`quick-nav-page-${currentPdfPage}`), {
            behavior: 'smooth',
            scrollMode: 'if-needed',
            block: 'start',
            inline: 'start',
        });
    }

    pageSelectedByClick($event: number): void {
        this._pdf.navigateTo($event);
    }

    readonly trackBy = (_index: number, item: number) => item;

    pageHasSelection(page: number) {
        return this.#multiSelectService.active() && !!this.#listingService.selected.find(a => a.pageNumber === page);
    }

    isPageExcluded(pageNumber: number): boolean {
        return this.#state.file().excludedPages.includes(pageNumber);
    }

    getViewedPage(viewedPages: ViewedPage[], pageNumber: number) {
        return viewedPages.find(p => p.page === pageNumber);
    }
}
