import { Component, Input, OnInit, ViewChild, ChangeDetectorRef } from '@angular/core';
import { DialogRef, DialogContentBase } from '@progress/kendo-angular-dialog';
import { NgForm } from '@angular/forms';
import { first } from 'rxjs/operators';
import { MD2MobSkill, MobSkillTarget } from '../../massive-darkness2.db.model';
import { MobSkillType } from '../../massive-darkness2.model.boss';
import { MD2MobSkillService } from '../../service/massive-darkness2.service';

@Component({
    selector: 'ngx-md2-mob-skill-editor',
    templateUrl: './md2-mob-skill-editor.component.html',
    styleUrls: ['./md2-mob-skill-editor.component.scss']
})
export class MD2MobSkillEditorComponent extends DialogContentBase implements OnInit {
    MobSkillType = MobSkillType;
    @Input() public data: MD2MobSkill;
    @Input() public mobInfoId: string;
    @Input() public selectedLevel: number = 1;
    @Input() public isAdding: boolean = false;
    @ViewChild('form') form: NgForm;

    public model: MD2MobSkill;
    public processing: boolean = false;
    public skillTypes: Array<{ value: MobSkillType; text: string }> = [];
    public skillTargets: Array<{ value: MobSkillTarget | null; text: string }> = [];
    public selectedSkillType: { value: MobSkillType; text: string } | null = null;
    public selectedSkillTarget: { value: MobSkillTarget | null; text: string } | null = null;

    constructor(
        public dialog: DialogRef,
        private mobSkillService: MD2MobSkillService,
        private cdr: ChangeDetectorRef
    ) {
        super(dialog);
        this.initializeEnums();
    }

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

    public initializeModel(): void {
        const typeValue = this.data?.type !== undefined && this.data?.type !== null ? this.data.type : MobSkillType.Combat;
        const targetValue = this.data?.skillTarget !== undefined ? this.data.skillTarget : null;

        this.model = {
            id: this.data?.id || '',
            seq: this.data?.seq ?? 0,
            level: this.data?.level ?? this.selectedLevel,
            mobInfoId: this.mobInfoId || this.data?.mobInfoId || '',
            type: typeValue,
            skillTarget: targetValue,
            clawRoll: this.data?.clawRoll ?? 0,
            skillRoll: this.data?.skillRoll ?? 1,
            name: this.data?.name || '',
            skillCondition: this.data?.skillCondition || '',
            description: this.data?.description || ''
        };

        // Set selected objects for dropdowns
        this.selectedSkillType = this.skillTypes.find(t => t.value === typeValue) || this.skillTypes[0] || null;
        this.selectedSkillTarget = this.skillTargets.find(t => t.value === targetValue) || this.skillTargets[0] || null;

        this.cdr.detectChanges();
    }

    private initializeEnums(): void {
        // Initialize MobSkillType options
        Object.keys(MobSkillType).filter(key => isNaN(Number(key))).forEach(key => {
            this.skillTypes.push({
                value: MobSkillType[key] as MobSkillType,
                text: key
            });
        });

        // Initialize MobSkillTarget options
        this.skillTargets.push({ value: null, text: 'None' });
        Object.keys(MobSkillTarget).filter(key => isNaN(Number(key))).forEach(key => {
            this.skillTargets.push({
                value: MobSkillTarget[key] as MobSkillTarget,
                text: key
            });
        });
    }

    public close(): void {
        this.dialog.close();
    }

    public save(): void {
        if (!this.processing) {
            this.processing = true;

            // Extract enum values from selected objects
            const mobSkill: MD2MobSkill = {
                ...this.model,
                type: this.selectedSkillType?.value ?? MobSkillType.Combat,
                skillTarget: this.selectedSkillTarget?.value ?? null,
                mobInfoId: this.mobInfoId || this.model.mobInfoId,
                level: this.model.level || this.selectedLevel
            };

            this.mobSkillService.createOrUpdate(mobSkill).pipe(first()).subscribe(result => {
                this.processing = false;
                this.dialog.close(result);
            }, error => {
                this.processing = false;
                console.error('Error saving mob skill:', error);
            });
        }
    }

    public get isValid(): boolean {
        if (!this.model) {
            return false;
        }
        const typeValid = this.selectedSkillType !== null && this.selectedSkillType !== undefined;
        return typeValid;
    }
}

