import { Clipboard } from '@angular/cdk/clipboard';
import { NgIf } from '@angular/common';
import { Component, computed, ElementRef, input, output } from '@angular/core';
import { getConfig, 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';
import { AnnotationReferencesListComponent } from '../annotation-references-list/annotation-references-list.component';
import { AnnotationWrapperComponent } from '../annotation-wrapper/annotation-wrapper.component';
import { HighlightsSeparatorComponent } from '../highlights-separator/highlights-separator.component';

@Component({
    selector: 'redaction-annotations-list',
    templateUrl: './annotations-list.component.html',
    styleUrls: ['./annotations-list.component.scss'],
    standalone: true,
    imports: [NgIf, HighlightsSeparatorComponent, AnnotationWrapperComponent, AnnotationReferencesListComponent],
})
export class AnnotationsListComponent extends HasScrollbarDirective {
    protected readonly isDocumine = getConfig().IS_DOCUMINE;
    readonly annotations = input.required<ListItem<AnnotationWrapper>[]>();
    readonly pagesPanelActive = output<boolean>();
    readonly displayedHighlightGroups = computed(() => {
        const isEarMarks = this._viewModeService.isEarmarks();
        let result: Record<number, EarmarkGroup> = {};

        if (isEarMarks) {
            const annotations = this.annotations();
            const earmarkGroups = this.#getEarmarksGroups(annotations);
            for (let idx = 0; idx < annotations.length; ++idx) {
                const group = earmarkGroups.find(h => h.startIdx === idx);
                if (group) {
                    result[idx] = group;
                }
            }
        }

        return result;
    });

    constructor(
        protected readonly _elementRef: ElementRef,
        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,
        private readonly clipboard: Clipboard,
    ) {
        super(_elementRef);
    }

    annotationClicked(annotation: AnnotationWrapper, $event: MouseEvent): void {
        if ($event.ctrlKey && $event.altKey) {
            this.clipboard.copy(annotation.id);
        }
        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);
        this._annotationManager.setSelectedFromWorkload();
    }

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

    #getEarmarksGroups(annotations: ListItem<AnnotationWrapper>[]) {
        const earmarksGroups: EarmarkGroup[] = [];

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

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

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