import {
    ChangeDetectionStrategy,
    Component,
    EventEmitter,
    Input,
    OnChanges,
    Output,
    SimpleChanges,
    ViewChild,
} from '@angular/core';
import { IDateOption } from './date-select/date-select.component';
import { Carousel } from 'primeng/carousel';

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

type IPageChangeEvent = {
    page: number;
};

@Component({
    selector: 'date-tabs',
    templateUrl: './date-tabs.component.html',
    styleUrls: ['./date-tabs.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class DateTabsComponent implements OnChanges {
    @ViewChild(Carousel) carousel: Carousel;

    @Input() caption!: string;
    @Input() tabs: IDateTab[];
    @Input() tabsPerPage = 7;

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

    currentPage = 0;
    dateOptions: IDateOption[];

    ngOnChanges(changes: SimpleChanges) {
        if ('tabs' in changes || 'tabsPerPage' in changes) {
            this.onTabsChange();
        }

        if ('tabs' in changes) {
            this.dateOptions = this.getDateOptions();
        }
    }

    onSelect(value: unknown) {
        this.tabClick.emit(value);
    }

    onPage(event: IPageChangeEvent) {
        this.currentPage = event.page;
    }

    private scrollToPage(page: number) {
        if (!this.carousel) {
            return;
        }

        if (page > this.currentPage) {
            this.carousel.navForward({}, page);
        }

        if (page < this.currentPage) {
            this.carousel.navBackward({}, page);
        }
    }

    private onTabsChange() {
        const page = computeCurrentPage(this.tabs, this.tabsPerPage);
        // Scrolling will not work without timeout
        setTimeout(() => {
            this.scrollToPage(page);
            this.currentPage = page;
        });
    }

    private getDateOptions(): IDateOption[] {
        return this.tabs.map((tab) => {
            return {
                label: tab.mobileLabel,
                value: tab.value,
                disabled: tab.disabled,
                active: tab.active,
            };
        });
    }
}

function computeCurrentPage(tabs: IDateTab[], tabsPerPage) {
    const activeTabIndex = tabs.findIndex((tab) => tab.active);

    if (activeTabIndex === -1) {
        return 0;
    }

    return Math.floor(activeTabIndex / tabsPerPage);
}
