import { Component, OnInit, ViewChild } from '@angular/core';
import { GridComponent, GridDataResult } from '@progress/kendo-angular-grid';
import { State, process } from '@progress/kendo-data-query';
import { first } from 'rxjs/operators';
import { MD2HeroProfile, HeroClass, MD2Icon } from '../massive-darkness2.model';
import { MD2HeroProfileService } from '../service/massive-darkness2.service';
import { MD2HeroProfileEditorComponent } from './md2-hero-profile-editor/md2-hero-profile-editor.component';
import { DialogService } from '@progress/kendo-angular-dialog';
import { MsgBoxService } from '../../../services/msg-box.service';

@Component({
    selector: 'ngx-md2-hero-profile-maintenance',
    templateUrl: './md2-hero-profile-maintenance.component.html',
    styleUrls: ['./md2-hero-profile-maintenance.component.scss']
})
export class MD2HeroProfileMaintenanceComponent implements OnInit {
    @ViewChild('grid') grid: GridComponent;
    MD2Icon = MD2Icon;
    public gridData: GridDataResult = { data: [], total: 0 };
    private allData: MD2HeroProfile[] = [];
    private lastSelectedHeroClass: HeroClass;
    public gridState: State = {
        skip: 0,
        take: 10,
        sort: [{
            field: 'title',
            dir: 'asc'
        }],
        filter: {
            logic: 'and',
            filters: []
        },
        group: [{
            field: 'heroClass',
            dir: 'asc'
        }]
    };
    public isLoading: boolean = false;

    constructor(
        private heroProfileService: MD2HeroProfileService,
        private dialogService: DialogService,
        private msgBoxService: MsgBoxService
    ) {
    }

    ngOnInit(): void {
        this.loadData();
    }

    public loadData(): void {
        this.isLoading = true;
        this.heroProfileService.getAll().pipe(first()).subscribe(result => {
            this.allData = result;
            this.processGridData();
            this.isLoading = false;
        });
    }

    public processGridData(): void {
        // Normalize filter state to handle null/undefined/empty filters
        let normalizedFilter: { logic: 'and' | 'or'; filters: any[] } = { logic: 'and', filters: [] };
        if (this.gridState.filter) {
            const filters = this.gridState.filter.filters || [];
            if (filters.length > 0) {
                normalizedFilter = this.gridState.filter;
            }
        }

        const normalizedState: State = {
            ...this.gridState,
            filter: normalizedFilter
        };

        this.gridData = process(this.allData, normalizedState);
    }

    public addHandler(): void {
        const editorData = { heroClass: this.lastSelectedHeroClass || HeroClass.Berserker } as MD2HeroProfile;
        const dialogRef = this.dialogService.open({
            title: 'Add New Hero Profile',
            content: MD2HeroProfileEditorComponent,
            width: '90vw',
            height: 600
        });

        const editor = dialogRef.content.instance;
        editor.isAdding = true;
        editor.data = editorData;

        // Force model re-initialization after data is set
        setTimeout(() => {
            editor.initializeModel();
        }, 0);

        dialogRef.result.subscribe((result: MD2HeroProfile) => {
            if (result) {
                this.lastSelectedHeroClass = result.heroClass;
                this.loadData();
            }
        });
    }

    public editHandler({ dataItem }: { dataItem: MD2HeroProfile }): void {
        const dialogRef = this.dialogService.open({
            title: 'Edit Hero Profile',
            content: MD2HeroProfileEditorComponent,
            width: '90vw',
            height: 600
        });

        const editor = dialogRef.content.instance;
        editor.isAdding = false;
        editor.data = JSON.parse(JSON.stringify(dataItem));

        // Force model re-initialization after data is set
        setTimeout(() => {
            editor.initializeModel();
        }, 0);

        dialogRef.result.subscribe(result => {
            if (result) {
                this.loadData();
            }
        });
    }

    public removeHandler({ dataItem }: { dataItem: MD2HeroProfile }): void {
        this.msgBoxService.showConfirmDeleteBox().pipe(first()).subscribe(answer => {
            if (answer === true) {
                this.isLoading = true;
                this.heroProfileService.delete(dataItem.id).pipe(first()).subscribe(result => {
                    this.loadData();
                });
            }
        });
    }

    public getHeroClassName(heroClass: HeroClass): string {
        return HeroClass[heroClass] || '';
    }
}

