import { Component } from '@angular/core';
import { DataService } from 'src/services/data/data.service';
import { ModalService } from 'src/services/modal/modal.service';
import { DetailsService } from 'src/services/details/details.service';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { Spell } from 'src/interfaces/interfaces';
import { FullSpellcardComponent } from 'src/app/shared-components/full-spellcard/full-spellcard.component';
import { FavoriteSpellsModalComponent } from './favorite-spells-modal/favorite-spells-modal.component';
import { TranslateService } from '@ngx-translate/core';
import { UtilsService } from 'src/services/utils/utils.service';

@Component({
  selector: 'spell-table',
  templateUrl: './spell-table.component.html',
  styleUrls: ['./spell-table.component.scss'],
})
export class SpellTableComponent {
  public spells!: Spell[];
  private preparedSpells!: Spell[];
  public newSpellName: string = '';

  public constructor(
    public dataAccessor: DataService,
    private modalAccessor: ModalService,
    public detailsAccessor: DetailsService,
    public translate: TranslateService,
    public utils: UtilsService,
  ) {}

  public ngOnInit(): void {
    this.spells = this.dataAccessor.favoriteSpells;
    this.preparedSpells = this.dataAccessor.getAllPreparedSpells();
  }

  public showFullSpellcard(spellIndex: number): void {
    const spell = this.spells[spellIndex];
    this.modalAccessor.openModal(FullSpellcardComponent, {
      spell: spell,
      isFromDashboard: true,
    });
    const resultSubscription = this.modalAccessor.result$.subscribe(
      (result) => {
        resultSubscription.unsubscribe();
        if (result.state === 'remove') {
          this.spells.splice(spellIndex, 1);
          this.updateSpellsInDatabase();
        } else if (result.state === 'removeFromFavorites') {
          this.dataAccessor.removeFavoriteSpell(spell);
        }
      },
    );
  }

  public openModal(): void {
    this.modalAccessor.openModal(FavoriteSpellsModalComponent, {
      preparedSpells: this.preparedSpells,
      selectedSpells: this.spells,
    });
    const resultSubscription = this.modalAccessor.result$.subscribe(
      (result) => {
        if (result.state === 'update') {
          this.spells = result.data;
          this.updateSpellsInDatabase();
        }
        resultSubscription.unsubscribe();
      },
    );
  }

  public deleteSpell(index: number): void {
    this.spells.splice(index, 1);
    this.updateSpellsInDatabase();
  }

  public dropSpells(event: CdkDragDrop<string[]>): void {
    moveItemInArray(this.spells, event.previousIndex, event.currentIndex);
    this.updateSpellsInDatabase();
  }

  public updateSpellsInDatabase(): void {
    this.dataAccessor.favoriteSpells = this.spells;
  }
}
