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

@Component({
    selector: 'redaction-pages',
    templateUrl: './pages.component.html',
    styleUrls: ['./pages.component.scss'],
})
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>;
    @Input({ required: true }) displayedAnnotations: Map<number, AnnotationWrapper[]>;
    readonly viewedPages$ = inject(ViewedPagesMapService).get$(this.#state.fileId);

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

    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);
    }

    hasOnlyManualRedactionsAndIsExcluded(pageNumber: number): boolean {
        const hasOnlyManualRedactions = this.displayedAnnotations.get(pageNumber)?.every(annotation => annotation.manual);
        return hasOnlyManualRedactions && this.#state.file().excludedPages.includes(pageNumber);
    }

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