import {
    ChangeDetectionStrategy,
    Component,
    EventEmitter,
    HostListener,
    Input,
    OnChanges,
    Output,
    SimpleChanges,
    ViewChild,
} from '@angular/core';
import { Dropdown } from 'primeng/dropdown';

export type IDateOption<T = unknown> = {
    label: string;
    disabled: boolean;
    value: T;
    active?: boolean;
};

@Component({
    selector: 'date-select',
    templateUrl: './date-select.component.html',
    styleUrls: ['./date-select.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DateSelectComponent implements OnChanges {
    @ViewChild(Dropdown) dropdown: Dropdown;

    @Input() options!: IDateOption[];
    @Input() caption!: string;

    @Output() dateChange = new EventEmitter<unknown>();

    selectedValue: unknown;

    ngOnChanges(changes: SimpleChanges) {
        if ('options' in changes) {
            this.selectedValue = this.getSelectedValue();
        }
    }

    onChange(value: unknown) {
        this.dateChange.emit(value);
    }

    @HostListener('body:scroll')
    private onScroll() {
        if (this.dropdown && this.dropdown?.overlayVisible) {
            this.dropdown.hide({});
        }
    }

    private getSelectedValue() {
        const selectedOption = this.options.find((option) => option.active);

        return selectedOption?.value;
    }
}
