import { Component, OnInit, ViewContainerRef } from '@angular/core';
import { actionsExecuting, ActionsExecuting } from '@ngxs-labs/actions-executing';
import { Select, Store } from '@ngxs/store';
import { ModalDialogOptions, ModalDialogService } from '@nativescript/angular';
import { Observable } from 'rxjs';
import { withLatestFrom } from 'rxjs/operators';
import { SortDirection, SortParams } from '~/pages/event/types/EventSorting';
import { ActionBarAction, TOP_ACTION_BAR_HEIGHT } from '~/pages/event/components/common/disappearing-scroll-action-bar/disappearing-scroll-action-bar.component';
import { SortSearchTag, ModalType } from '~/pages/event/types/common.types';
import { LoadUnits, SetUnitSearchParams, SetUnitSortParams } from './../../state-mgmt/unit-search.actions';
import { UnitSearch, UnitSearchState, UnitSortKey } from '../../state-mgmt/unit-search.state';
import { UnitAllOutput } from './../../entities/output/unitAllOutput';
import { SortModalComponent } from '~/pages/event/components/common/sort-modal/sort-modal.component';
import { Picker, sortItems } from '~/pages/event/util';
import { formattedAlignments, UnitSearchModalComponent } from '../../components/unit-search-modal/unit-search-modal.component';
import { sortIcon, searchIcon } from '~/constants/icons';


export const formattedUnitSortKeys: Array<Picker> = [
    { key: UnitSortKey.NAME, label: 'Dle jména' },
    { key: UnitSortKey.REGISTRATION_NUMBER, label: 'Dle evidenčního čísla' },
    { key: UnitSortKey.TYPE, label: 'Dle typu' },
    { key: UnitSortKey.LOCATION, label: 'Dle místa působení' },
];

@Component({
    selector: 'UnitSearchList',
    moduleId: module.id,
    templateUrl: './unit-list-page.component.html',
})
export class UnitListPageComponent implements OnInit {
    @Select(actionsExecuting([LoadUnits]))
    isLoading$: Observable<ActionsExecuting>;
    @Select(UnitSearchState.getUnits)
    unitList$: Observable<UnitAllOutput[]>;
    @Select(UnitSearchState.getSortParams)
    sortParams$: Observable<SortParams>;
    @Select(UnitSearchState.getSearchParams)
    searchParams$: Observable<UnitSearch>;
    @Select(UnitSearchState.isSearchSortDirty)
    isSearchSortDirty$: Observable<boolean>;

    topBarHeight = TOP_ACTION_BAR_HEIGHT;

    unitList: UnitAllOutput[];
    _sortParams: SortParams;
    searchParams: UnitSearch;
    isTopBarVisible: boolean = true;

    actionBarActions: ActionBarAction[] = [
        { type: 'sort', icon: sortIcon },
        { type: 'search', icon: searchIcon },
    ]
    constructor(
        private store: Store,
        private _vcRef: ViewContainerRef,
        private _modalService: ModalDialogService,

    ) {
    }

    tags: Array<SortSearchTag> = []
    paramLabels = {
        [UnitSortKey.NAME]: "Název",
        [UnitSortKey.REGISTRATION_NUMBER]: "Evidenční číslo",
        [UnitSortKey.TYPE]: 'Typ',
        [SortDirection.ASC]: 'Vzestupně',
        [SortDirection.DESC]: 'Sestupně',
    }


    refreshTags() {
        const {
            name, location, accountNumber, ic,
            registrationNumber, regNumberStart, alignment
        } = this.store.selectSnapshot(UnitSearchState.getSearchParams)
        const sortParams = this.store.selectSnapshot(UnitSearchState.getSortParams)
        const alignString = alignment && alignment.toString()
        const align = formattedAlignments.find(i => i.key === alignString)
        this.tags = [
            { text: `Seřaděno dle: ${this.paramLabels[sortParams.sortByKey]}`, modalType: ModalType.Sort },
            { text: `Směr: ${this.paramLabels[sortParams.sortDirection]}`, modalType: ModalType.Sort },
            name && { text: `Název: ${name}`, modalType: ModalType.Search },
            registrationNumber && { text: `Evidenční číslo: ${registrationNumber}`, modalType: ModalType.Search },
            regNumberStart && { text: `Evidenční číslo začína: ${regNumberStart ? 'ano' : 'ne'}`, modalType: ModalType.Search },
            location && { text: `Místo působení: ${location}`, modalType: ModalType.Search },
            align && { text: `Zaměření: ${align && align.label}`, modalType: ModalType.Search },
            accountNumber && { text: `Bankovní účet: ${accountNumber}`, modalType: ModalType.Search },
            ic && { text: `IČ: ${ic}`, modalType: ModalType.Search },
        ].filter(s => s);
    }

    refreshUnits(forceRefresh: boolean = false) {
        if (forceRefresh || this.store.selectSnapshot(UnitSearchState.isSearchSortDirty)) {
            this.unitList = []
            this.store.dispatch(new LoadUnits())
                .pipe(withLatestFrom(this.unitList$, this.sortParams$, this.searchParams$))
                .subscribe(([_, units, sortParams, searchParams]) => {
                    this.searchParams = searchParams;
                    this.unitList = sortItems(units, sortParams);
                    this.refreshTags()
                })
        }
    }

    ngOnInit(): void {
        this.refreshUnits(true);
    }

    resetSortSearch() {
        this.store.dispatch([new SetUnitSortParams(), new SetUnitSearchParams()])
            .subscribe(() => {
                this.refreshUnits(true);
            })
    }


    openSortingModal() {
        this._sortParams = this.store.selectSnapshot(UnitSearchState.getSortParams)
        const options: ModalDialogOptions = {
            viewContainerRef: this._vcRef,
            context: { sortParams: this._sortParams, formattedSortByKeys: formattedUnitSortKeys },
            fullscreen: false,
        };
        this._modalService.showModal(SortModalComponent, options)
            .then((formResult: SortParams) => {
                if (formResult) {
                    this.store.dispatch(new SetUnitSortParams(formResult))
                        .pipe(withLatestFrom(this.unitList$, this.sortParams$))
                        .subscribe(([_, events, sortParams]) => {
                            this._sortParams = sortParams
                            this.refreshTags()
                            this.unitList = sortItems(events, sortParams);
                        })
                }
            });
    }

    onAction(action: ActionBarAction) {
        if (action.type === "sort") {
            this.openSortingModal();
        } else if (action.type === "search") {
            this.openSearchModal();
        }
    }

    openSearchModal() {
        this.searchParams = this.store.selectSnapshot(UnitSearchState.getSearchParams)
        const options: ModalDialogOptions = {
            viewContainerRef: this._vcRef,
            context: { ...this.searchParams },
            fullscreen: false,
        };

        this._modalService.showModal(UnitSearchModalComponent, options)
            .then((formResult: UnitSearch) => {
                if (formResult) {
                    this.store.dispatch(new SetUnitSearchParams(formResult))
                        .subscribe((_) => {
                            this.refreshUnits();
                        })
                }

            });
    }
}
