import { Component, ElementRef, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { RouterExtensions } from '@nativescript/angular';
import { FeedbackType } from 'nativescript-feedback';
import { RadDataFormComponent } from 'nativescript-ui-dataform/angular';
import { action } from '@nativescript/core/ui/dialogs';
import { Degree } from '~/pages/event/entities/camp-event-participant.types';
import { errorFeedback, errorFeedbackOperator } from '~/pages/event/state-mgmt/gen/gen-event-new.state';
import { Picker } from '~/pages/event/util';
import { feedbackMessage } from '~/pages/material/utils/feedback-messages';
import { deleteIcon } from '~/constants/icons';

export interface ParticipantForm {
    firstName: string;
    lastName: string;
    nickName: string;
    note: string;
}
export interface NewParticipantFormResult {
    info: ParticipantForm;
    degrees: Degree[]
}

@Component({
    selector: 'ParticipantForm',
    moduleId: module.id,
    templateUrl: './participant-form.component.html',
    styleUrls: ['_participant-form.component.scss']
})
export class ParticipantFormComponent {

    personForm: ParticipantForm = { firstName: '', lastName: '', nickName: '', note: '' }

    deleteIcon = deleteIcon;
    @ViewChild("myDataForm", { static: false })
    dataFormComp: RadDataFormComponent;
    @ViewChild("resultLabel", { static: false })
    resultLabel: ElementRef;
    @Output()
    onSubmit = new EventEmitter<NewParticipantFormResult>()

    selectedDegrees: Degree[] = [];

    @Input()
    degrees: Degree[]

    constructor(
        private routerExtensions: RouterExtensions,

    ) {
    }

    handleSubmit() {
        const hasErrors = this.dataFormComp.dataForm.hasValidationErrors();
        if (!hasErrors) {
            this.onSubmit.emit({ info: this.personForm, degrees: this.selectedDegrees })
        }
    }

    handleAddDegree() {
        let options = {
            title: "Tituly",
            message: "Přidat nový titul",
            cancelButtonText: "Zruš",
            actions: this.degrees.map(d => d.DisplayName)
        };

        action(options).then((result) => {
            const selDeg = this.degrees.find(d => d.DisplayName === result)
            if (selDeg) {
                if (this.selectedDegrees.find(d => d.ID == selDeg.ID)) {
                    feedbackMessage(FeedbackType.Error, 'Titul nepřidělen', 'Zadaný titul je již osobě přidělen')
                } else {
                    this.selectedDegrees = [...this.selectedDegrees, selDeg];
                }
            }
        });

    }
    removeDeg(deg: Degree) {
        this.selectedDegrees = this.selectedDegrees.filter(d => d.ID !== deg.ID);
    }


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

    public trackItem(index: number, item: Degree) {
        return item.ID;
    }


}
