import { Component, ViewChild, OnInit } from '@angular/core';
import { RouterExtensions } from '@nativescript/angular';
import { Select, Store } from '@ngxs/store';
import { Observable } from 'rxjs';
import { withLatestFrom } from 'rxjs/operators';
import * as dialogs from "@nativescript/core/ui/dialogs";
import { Picker } from '~/pages/event/util';
import { CampEventParticipantState } from '~/pages/event/state-mgmt/camp/camp-event-participant.state';
import { TeamMember } from '../../gen/gen-event-update-leader-modal/gen-event-update-leader-modal.component';
import { CampEventUpdateFunctions, LoadCampEventLeaders } from '~/pages/event/state-mgmt/camp/camp-event-detail.actions';
import { CampEventFunctionAllOutput } from '~/pages/event/entities/camp-event-detail.types';
import { CampEventDetailState } from '~/pages/event/state-mgmt/camp/camp-event-detail.state';
import { ActivatedRoute } from '@angular/router';
import { transitionOptions } from '~/constants/shared.constants';
import { CampPersonSearchContainerComponent } from '../../common/camp-person-search-container/camp-person-search-container.component';

export interface CampEventLeaderUpdateModalInput {
    members: TeamMember[],
    eventId: number,
    team: CampEventFunctionAllOutput[],
}
@Component({
    selector: 'CampEventUpdateLeadderPage',
    moduleId: module.id,
    templateUrl: './camp-event-update-leader-page.component.html',

})
export class CampEventUpdateLeaderPage implements OnInit {
    @ViewChild('personSearch', { static: true })
    personSearch: CampPersonSearchContainerComponent
    @Select(CampEventDetailState.getEventLeaderDetail)
    eventLeaders$: Observable<CampEventFunctionAllOutput[]>;
    members: TeamMember[];
    eventId: number;
    canSelectFunction: boolean = false;
    team: CampEventFunctionAllOutput[];
    eventName: any;
    constructor(
        private route: ActivatedRoute,
        private store: Store,
        private routerExtensions: RouterExtensions,
    ) {
    }
    noteForm = { note: '' }
    formattedPersonList$: Observable<Picker[]>;

    ngOnInit(): void {
        this.route.params.subscribe(params => {
            this.eventId = parseInt(params['id'], 10);
            this.store.dispatch(new LoadCampEventLeaders(this.eventId))
                .pipe(withLatestFrom(this.eventLeaders$)).subscribe(([_, res]) => {
                    this.team = res;
                    this.eventName = res.find(i => i.Event).Event;
                    this.members = this.team.map(t => ({
                        roleId: t.ID_EventFunctionType, memberId: t.ID_Person,
                        roleName: t.EventFunctionType, memberName: t.Person, note: t.Note,
                    }));
                    this.canSelectFunction = false
                })
        })
    }
    close() {
        this.personSearch.clear()
        setTimeout(() => {
            this.routerExtensions.navigate(['/event/campDetail/', this.eventId, 1], { transition: transitionOptions });
        }, 10);
    }

    deleteLeader(member: TeamMember) {
        member.memberId = null;
        member.memberName = null;
        member.note = null;
        this.canSelectFunction = !!this.personSearch.selectedPersonId
    }
    updateNote(member: TeamMember) {
        const opts = {
            title: "Upravit poznámku",
            message: "Poznámka",
            okButtonText: "Upravit",
            cancelButtonText: "Zrušit",
            defaultText: member.note,
        };
        dialogs.prompt(opts).then((r) => {
            member.note = r.text;
        });
    }

    assignFunction() {
        const userId = this.personSearch.selectedPersonId
        const personList = this.store.selectSnapshot(CampEventParticipantState.getPersonList)
        const person = personList.find(p => p.ID === userId)
        dialogs.action({
            title: 'Vyberte funkci',
            message: "Vyberte funkci pro " + person.DisplayName,
            cancelButtonText: "Zrušit",
            actions: this.members.map(p => p.roleName)
        }).then((result) => {
            const selectedMember = this.members.find(m => m.roleName === result);
            selectedMember.memberId = userId;
            selectedMember.note = this.noteForm.note;
            this.personSearch.clear()
            this.noteForm = { note: '' };
            selectedMember.memberName = personList.find(p => p.ID === userId).DisplayName
            this.canSelectFunction = false
        });
    }
    handleSelectedPerson(id: number) {
        this.canSelectFunction = !!id;
    }

    submit() {
        const merged = this.members
            .map(({ note, memberId, memberName, roleId, roleName }) => ({
                ...this.team.find(p => p.EventFunctionType === roleName),
                Note: note, ID_Person: memberId,
                ID_EventFunctionType: roleId, Person: memberName,
                EventFunctionType: roleName
            }))
        this.store.dispatch(new CampEventUpdateFunctions(this.eventId, merged))
            .subscribe(() => {
                this.routerExtensions.navigate(['/event/campDetail/', this.eventId, 1],
                    { transition: transitionOptions });
            })
    }

}
