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 { MD2MobInfo, GameBundle } from '../massive-darkness2.db.model';
import { MobType } from '../massive-darkness2.model';
import { MD2MobInfoService } from '../service/massive-darkness2.service';
import { MD2MobInfoDetailComponent } from './md2-mob-info-detail/md2-mob-info-detail.component';
import { MD2MobInfoEditorComponent } from './md2-mob-info-editor/md2-mob-info-editor.component';
import { DialogService } from '@progress/kendo-angular-dialog';
import { MsgBoxService } from '../../../services/msg-box.service';

@Component({
    selector: 'ngx-md2-mob-info-maintenance',
    templateUrl: './md2-mob-info-maintenance.component.html',
    styleUrls: ['./md2-mob-info-maintenance.component.scss']
})
export class MD2MobInfoMaintenanceComponent implements OnInit {
    @ViewChild('grid') grid: GridComponent;

    public gridData: GridDataResult = { data: [], total: 0 };
    private allData: MD2MobInfo[] = [];
    public gridState: State = {
        skip: 0,
        take: 10,
        sort: [{
            field: 'name',
            dir: 'asc'
        }],
        filter: {
            logic: 'and',
            filters: []
        },
        group: [{
            field: 'type',
            dir: 'asc'
        }]
    };
    public isLoading: boolean = false;

    constructor(
        private mobInfoService: MD2MobInfoService,
        private dialogService: DialogService,
        private msgBoxService: MsgBoxService
    ) {
    }

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

    public loadData(): void {
        this.isLoading = true;
        this.mobInfoService.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 = {} as MD2MobInfo;
        const dialogRef = this.dialogService.open({
            title: 'Add New Mob Info',
            content: MD2MobInfoEditorComponent,
            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 => {
            if (result) {
                this.loadData();
            }
        });
    }

    public editHandler({ dataItem }: { dataItem: MD2MobInfo }): void {
        const dialogRef = this.dialogService.open({
            title: 'Edit Mob Info',
            content: MD2MobInfoEditorComponent,
            width: '90vw',
            height: 600
        });

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

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

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

    public viewDetailHandler({ dataItem }: { dataItem: MD2MobInfo }): void {
        this.mobInfoService.getById(dataItem.id).pipe(first()).subscribe(mobInfo => {
            const dialogRef = this.dialogService.open({
                title: `Mob Info: ${mobInfo.name}`,
                content: MD2MobInfoDetailComponent,
                width: '90vw',
                height: 800
            });

            const detail = dialogRef.content.instance;
            detail.mobInfo = mobInfo;

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

    public getMobTypeName(type: MobType): string {
        return MobType[type] || '';
    }

    public getGameBundleName(bundle: GameBundle): string {
        return GameBundle[bundle] || '';
    }
}

