import {
  Component,
  inject,
  QueryList,
  TemplateRef,
  ViewChildren,
  ViewChild,
} from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { DataService } from 'src/services/data/data.service';
import { Router } from '@angular/router';
import { CharacterCardComponent } from './character-card/character-card.component';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-character-picker',
  templateUrl: './character-picker.component.html',
  styleUrls: ['./character-picker.component.scss'],
})
export class CharacterPickerComponent {
  public characters: any[] = [];
  public currentCharacter: string = '';
  private modalService = inject(NgbModal);

  @ViewChild('warning') warning!: TemplateRef<any>;
  @ViewChildren(CharacterCardComponent)
  characterCards!: QueryList<CharacterCardComponent>;

  public constructor(
    public dataService: DataService,
    private Router: Router,
    public translate: TranslateService,
  ) {
    this.dataService.dataLoaded = false;
    this.dataService.getCollection('characters').then((characters: any) => {
      this.characters = characters;
    });
  }

  ngAfterViewInit() {
    this.showWarning(this.warning);
  }

  /**
   * Navigates to the character creator page.
   */
  public addCharacter() {
    this.Router.navigate(['character/creator']);
  }

  /**
   * Opens the modal to ask the user if they really want to delete the character.
   * @param content The content that is to be displayed in the modal.
   * @param index The index of the character that is to be deleted.
   */
  open(content: TemplateRef<any>, index: number) {
    this.currentCharacter = this.characters[index].name;
    this.modalService
      .open(content, { ariaLabelledBy: 'modal-basic-title' })
      .result.then(
        (result) => {},
        (reason) => {
          if (reason == 'delete') {
            this.deleteCharacter(index);
          }
        },
      );
  }

  /**
   * Deletes a character from the list of characters.
   * @param index The index of the character to be deleted.
   */
  public deleteCharacter(index: number) {
    this.characters.splice(index, 1);
    this.dataService.deleteCollection(this.currentCharacter);
    this.dataService.deleteCollection('characters');
    // TODO: Find a better solution that looks smoother.
    setTimeout(() => {
      this.dataService.setCollection('characters', this.characters);
    }, 200);
    setTimeout(() => {
      this.characterCards.forEach((card) => {
        card.loadCharacterData();
      });
    }, 500);
  }

  /**
   * Sets the character name in the session storage and navigates to character tracker itself.
   * @param character The character name
   */
  public selectCharacter(character: any) {
    sessionStorage.setItem('characterName', character.name);
    this.Router.navigate(['journal']);
  }

  /**
   * Show a warning to the user if they have not acknowledged it yet.
   * The warning
   */
  showWarning(warning: TemplateRef<any>) {
    let warningWasAcknowledged = sessionStorage.getItem(
      'warningWasAcknowledged',
    );
    if (!warningWasAcknowledged) {
      this.modalService.open(warning, { ariaLabelledBy: 'modal-basic-title' });
    }
  }

  /**
   * The user has acknowledged the warning, so it will not be shown again in this session.
   */
  public acknowledgeWarning() {
    sessionStorage.setItem('warningWasAcknowledged', 'true');
  }
}
