import { Component, OnInit } from '@angular/core';
import { ModalDialogParams, RouterExtensions } from '@nativescript/angular';
import { action, } from '@nativescript/core/ui/dialogs';
import { WebApiService } from '~/core/services/web-api.service';
import { formattedCongEventRel, formattedCongScheduleType } from '~/pages/event/types/CongEventSearch';
import { UnitOutput } from '~/pages/event/entities/gen-event-new.types';
import { UnitSearchCriteria, UnitSearchOptions } from '~/pages/event/types/UnitSearch';
import { Picker, loadUnits } from '~/pages/event/util';

export interface CongEventSearchForm {
    schedule: string;
    relation: string;
    unitId: string;
}

@Component({
    selector: 'CongEventSearchModalComponent',
    moduleId: module.id,
    templateUrl: './cong-event-search-modal.component.html',
})
export class CongEventSearchModalComponent implements OnInit {

    searchParams: CongEventSearchForm;
    unitForm = { text: '' };

    formattedEventRel = formattedCongEventRel
    formattedSchedule = formattedCongScheduleType;
    noData = { key: '', label: 'Pořadatelé nenalezeni' }
    formattedUnits: Array<Picker> = [];

    units: UnitOutput[] = [];
    constructor(
        private routerExtensions: RouterExtensions,
        private params: ModalDialogParams,
        private webApiService: WebApiService,
    ) {
    }

    ngOnInit(): void {
        const { searchParams, selectedUnitData } = this.params.context;
        if (selectedUnitData) {
            this.formattedUnits = [{ key: searchParams.unitId, label: selectedUnitData.SortName }]
            this.units = [selectedUnitData]
        }

        this.searchParams = { ...searchParams, unitId: searchParams.unitId || '' };

    }

    onSearchClick() {
        let options = {
            title: "Vyhledat podle",
            message: "Vyber",
            cancelButtonText: "Storno",
            actions: UnitSearchCriteria.map(v => v.label)
        };

        action(options).then((result) => {
            const selectedCrit = UnitSearchCriteria.find(c => c.label === result)
            loadUnits(this.webApiService, {
                criteria: UnitSearchOptions[selectedCrit.key],
                text: this.unitForm.text
            })
                .then((units: UnitOutput[]) => {
                    if (units.length === 0) {
                        this.formattedUnits = [this.noData]
                        this.units = units;
                        alert('Pořadatelé nebyly nalezeni')
                    } else {
                        this.units = units;
                        this.formattedUnits = [{ key: '', label: 'vše' },
                        ...units.map(({ ID, SortName }) =>
                            ({ label: SortName, key: ID.toString() }))]
                        action({
                            title: 'Vyberte pořadatele',
                            message: "Vyberte z nalezených pořadatelů",
                            cancelButtonText: "Zrušit",
                            actions: units.map(p => p.SortName)
                        }).then((result) => {
                            const { ID } = units.find(u => u.SortName === result);
                            this.searchParams = {
                                ...this.searchParams,
                                unitId: ID.toString(),
                            }
                        });
                    }

                }).catch(() => {
                    this.units = [];
                    this.formattedUnits = [this.noData]
                })
        });

    }

    close() {
        this.params.closeCallback();
    }

    submit() {
        const { schedule, relation, unitId } = this.searchParams
        this.params.closeCallback({
            schedule, relation,
            unit: unitId ? this.units.find(u => u.ID === parseInt(unitId, 10)) : null

        });
    }

    onBackButton(): void {
        this.routerExtensions.back();
    }
}