import { ChangeDetectorRef, Component, computed, ElementRef, EventEmitter, Input, Output } from '@angular/core';
import { HasScrollbarDirective } from '@iqser/common-ui';
import { FilterService } from '@iqser/common-ui/lib/filtering';
import { IqserEventTarget } from '@iqser/common-ui/lib/utils';
import { AnnotationWrapper } from '@models/file/annotation.wrapper';
import { ListItem } from '@models/file/list-item';
import { EarmarkGroup } from '@red/domain';
import { UserPreferenceService } from '@users/user-preference.service';
import { REDAnnotationManager } from '../../../pdf-viewer/services/annotation-manager.service';
import { AnnotationReferencesService } from '../../services/annotation-references.service';
import { AnnotationsListingService } from '../../services/annotations-listing.service';
import { MultiSelectService } from '../../services/multi-select.service';
import { ViewModeService } from '../../services/view-mode.service';

@Component({
    selector: 'redaction-annotations-list',
    templateUrl: './annotations-list.component.html',
    styleUrls: ['./annotations-list.component.scss'],
})
export class AnnotationsListComponent extends HasScrollbarDirective {
    @Input({ required: true }) annotations: ListItem<AnnotationWrapper>[];
    @Output() readonly pagesPanelActive = new EventEmitter<boolean>();
    readonly #earmarkGroups = computed(() => {
        if (this._viewModeService.isEarmarks()) {
            return this.#getEarmarksGroups();
        }
        return [] as EarmarkGroup[];
    });

    constructor(
        protected readonly _elementRef: ElementRef,
        protected readonly _changeDetector: ChangeDetectorRef,
        private readonly _multiSelectService: MultiSelectService,
        private readonly _filterService: FilterService,
        private readonly _userPreferenceService: UserPreferenceService,
        private readonly _viewModeService: ViewModeService,
        private readonly _annotationManager: REDAnnotationManager,
        private readonly _listingService: AnnotationsListingService,
        readonly annotationReferencesService: AnnotationReferencesService,
    ) {
        super(_elementRef, _changeDetector);
    }

    annotationClicked(annotation: AnnotationWrapper, $event: MouseEvent): void {
        if (this._userPreferenceService.isIqserDevMode) {
            console.log('Selected Annotation:', annotation);
        }

        if (($event?.target as IqserEventTarget)?.localName === 'input') {
            return;
        }

        this.pagesPanelActive.emit(false);

        if (this._listingService.isSelected(annotation)) {
            this._listingService.deselect(annotation);
            return this._annotationManager.deselect(annotation);
        }

        const canMultiSelect = this._multiSelectService.enabled();
        if (canMultiSelect && ($event?.ctrlKey || $event?.metaKey) && this._listingService.selected.length > 0) {
            this._multiSelectService.activate();
        }
        this._listingService.selectAnnotations(annotation);
    }

    referenceClicked(annotation: AnnotationWrapper): void {
        this.annotationClicked(annotation, null);
        if (this._filterService.filtersEnabled('primaryFilters')) {
            this._filterService.toggleFilter('primaryFilters', annotation.superType, true);
        }
    }

    showHighlightGroup(idx: number): EarmarkGroup {
        return this._viewModeService.isEarmarks() && this.#earmarkGroups().find(h => h.startIdx === idx);
    }

    protected readonly _trackBy = (index: number, listItem: ListItem<AnnotationWrapper>) => listItem.item.id;

    #getEarmarksGroups() {
        const earmarksGroups: EarmarkGroup[] = [];

        if (!this.annotations?.length) {
            return earmarksGroups;
        }

        let lastGroup: EarmarkGroup;
        for (let idx = 0; idx < this.annotations.length; ++idx) {
            if (idx === 0 || this.annotations[idx].item.color !== this.annotations[idx - 1].item.color) {
                if (lastGroup) {
                    earmarksGroups.push(lastGroup);
                }
                lastGroup = { startIdx: idx, length: 1, color: this.annotations[idx].item.color };
            } else {
                lastGroup.length += 1;
            }
        }

        earmarksGroups.push(lastGroup);
        return earmarksGroups;
    }
}
