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 { MD2HeroProfile, HeroClass } from '../../massive-darkness2.model';
import { MD2HeroProfileService } from '../../service/massive-darkness2.service';

@Component({
  selector: 'ngx-md2-hero-profile-editor',
  templateUrl: './md2-hero-profile-editor.component.html',
  styleUrls: ['./md2-hero-profile-editor.component.scss']
})
export class MD2HeroProfileEditorComponent extends DialogContentBase implements OnInit {
  @Input() public data: MD2HeroProfile;
  @Input() public isAdding: boolean = false;
  @ViewChild('form') form: NgForm;

  public model: MD2HeroProfile;
  public processing: boolean = false;
  public heroClasses: Array<{ value: HeroClass; text: string }> = [];
  public selectedHeroClass: { value: HeroClass; text: string } | null = null;

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

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

  public initializeModel(): void {
    const classValue = this.data?.heroClass !== undefined && this.data?.heroClass !== null ? this.data.heroClass : HeroClass.Berserker;

    this.model = {
      id: this.data?.id || '',
      heroClass: classValue,
      title: this.data?.title || '',
      hp: this.data?.hp || 0,
      mana: this.data?.mana || 0,
      skillHtml: this.data?.skillHtml || '',
      shadowSkillHtml: this.data?.shadowSkillHtml || ''
    };

    // Set selected object for dropdown
    this.selectedHeroClass = this.heroClasses.find(c => c.value === classValue) || this.heroClasses[0] || null;

    this.cdr.detectChanges();
  }

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

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

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

      // Extract enum value from selected object
      const heroProfile: MD2HeroProfile = {
        ...this.model,
        heroClass: this.selectedHeroClass?.value ?? HeroClass.Berserker
      };

      this.heroProfileService.createOrUpdate(heroProfile).pipe(first()).subscribe(result => {
        this.processing = false;
        this.dialog.close(result);
      }, error => {
        this.processing = false;
        console.error('Error saving hero profile:', error);
      });
    }
  }

  public get isValid(): boolean {
    if (!this.model) {
      return false;
    }
    const titleValid = true;// this.model.title && this.model.title.trim().length > 0;
    const classValid = this.selectedHeroClass !== null && this.selectedHeroClass !== undefined;
    return titleValid && classValid;
  }
}

