import {Component, DestroyRef, inject, OnInit} from '@angular/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {Song} from '../../../services/song';
import {ReactiveFormsModule} from '@angular/forms';
import {ActivatedRoute, Router, RouterStateSnapshot} from '@angular/router';
import {SongService} from '../../../services/song.service';
import {EditService, SongFormGroup} from '../edit.service';
import {first, map, switchMap} from 'rxjs/operators';
import {startWith} from 'rxjs';
import {KEYS} from '../../../services/key.helper';
import {COMMA, ENTER} from '@angular/cdk/keycodes';
import {MatChipGrid, MatChipInput, MatChipInputEvent, MatChipRow} from '@angular/material/chips';
import {faExternalLinkAlt, faSave, faTimesCircle} from '@fortawesome/free-solid-svg-icons';
import {MatDialog} from '@angular/material/dialog';
import {SaveDialogComponent} from './save-dialog/save-dialog.component';
import {TextRenderingService} from '../../../services/text-rendering.service';
import {ChordValidationIssue} from '../../../services/chord';

import {CardComponent} from '../../../../../widget-modules/components/card/card.component';
import {MatFormField, MatLabel, MatSuffix} from '@angular/material/form-field';
import {MatInput} from '@angular/material/input';
import {MatSelect} from '@angular/material/select';
import {MatOption} from '@angular/material/core';
import {CdkTextareaAutosize} from '@angular/cdk/text-field';
import {SongTextComponent} from '../../../../../widget-modules/components/song-text/song-text.component';
import {FaIconComponent} from '@fortawesome/angular-fontawesome';
import {MatTooltip} from '@angular/material/tooltip';
import {ButtonRowComponent} from '../../../../../widget-modules/components/button-row/button-row.component';
import {ButtonComponent} from '../../../../../widget-modules/components/button/button.component';
import {SongTypePipe} from '../../../../../widget-modules/pipes/song-type-translater/song-type.pipe';
import {LegalOwnerPipe} from '../../../../../widget-modules/pipes/legal-owner-translator/legal-owner.pipe';
import {LegalTypePipe} from '../../../../../widget-modules/pipes/legal-type-translator/legal-type.pipe';
import {KeyPipe} from '../../../../../widget-modules/pipes/key-translator/key.pipe';
import {StatusPipe} from '../../../../../widget-modules/pipes/status-translater/status.pipe';

@Component({
  selector: 'app-edit-song',
  templateUrl: './edit-song.component.html',
  styleUrls: ['./edit-song.component.less'],
  imports: [
    CardComponent,
    ReactiveFormsModule,
    MatFormField,
    MatLabel,
    MatInput,
    MatSelect,
    MatOption,
    CdkTextareaAutosize,
    SongTextComponent,
    MatChipGrid,
    MatChipRow,
    FaIconComponent,
    MatChipInput,
    MatSuffix,
    MatTooltip,
    ButtonRowComponent,
    ButtonComponent,
    SongTypePipe,
    LegalOwnerPipe,
    LegalTypePipe,
    KeyPipe,
    StatusPipe,
  ],
})
export class EditSongComponent implements OnInit {
  public dialog = inject(MatDialog);
  public song: Song | null = null;
  public form = {} as SongFormGroup;
  public keys = KEYS;
  public types = SongService.TYPES;
  public status = SongService.STATUS;
  public legalOwner = SongService.LEGAL_OWNER;
  public legalType = SongService.LEGAL_TYPE;
  public flags: string[] = [];
  public readonly separatorKeysCodes: number[] = [ENTER, COMMA];
  public faRemove = faTimesCircle;
  public faSave = faSave;
  public faLink = faExternalLinkAlt;
  public songtextFocus = false;
  public chordValidationIssues: ChordValidationIssue[] = [];
  private activatedRoute = inject(ActivatedRoute);
  private songService = inject(SongService);
  private editService = inject(EditService);
  private router = inject(Router);
  private textRenderingService = inject(TextRenderingService);
  private destroyRef = inject(DestroyRef);

  public ngOnInit(): void {
    this.activatedRoute.params
      .pipe(
        map(param => param as {songId: string}),
        map(param => param.songId),
        switchMap(songId => this.songService.read$(songId)),
        first(),
        takeUntilDestroyed(this.destroyRef)
      )
      .subscribe(song => {
        this.song = song;
        if (!song) return;
        this.form = this.editService.createSongForm(song);
        this.form.controls.flags.valueChanges.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(value => this.onFlagsChanged(value));
        this.form.controls.text.valueChanges.pipe(startWith(this.form.controls.text.value), takeUntilDestroyed(this.destroyRef)).subscribe(text => {
          this.updateChordValidation(text);
        });
        this.onFlagsChanged(this.form.controls.flags.value);
      });
  }

  public async onSave(): Promise<void> {
    if (!this.song || this.form.invalid) return;
    const data = this.form.getRawValue() as Partial<Song>;
    await this.songService.update$(this.song.id, data);
    this.form.markAsPristine();
    await this.router.navigateByUrl('songs/' + this.song.id);
  }

  public removeFlag(flag: string): void {
    const flags = this.flags.filter(_ => _ !== flag);
    this.form.controls.flags.setValue(flags.join(';'));
  }

  public addFlag(event: MatChipInputEvent): void {
    const input = event.input;
    const value = event.value;

    if ((value || '').trim()) {
      const flags = [...this.flags, value.trim()];
      this.form.controls.flags.setValue(flags.join(';'));
    }

    if (input) {
      input.value = '';
    }
  }

  public askForSave(nextState: RouterStateSnapshot): boolean {
    if (!this.form.dirty) {
      return true;
    }

    const dialogRef = this.dialog.open(SaveDialogComponent, {
      width: '350px',
    });

    dialogRef.afterClosed().subscribe((save: boolean) => {
      void this.onSaveDialogAfterClosed(save, nextState.url).then();
    });

    return false;
  }

  private onFlagsChanged(flagArray: string): void {
    if (!flagArray) {
      this.flags = [];
      return;
    }

    this.flags = flagArray.split(';').filter(_ => !!_);
  }

  private updateChordValidation(text: string): void {
    const control = this.form.controls.text;
    this.chordValidationIssues = this.textRenderingService.validateChordNotation(text ?? '');

    const errors = {...(control.errors ?? {})};
    if (this.chordValidationIssues.length > 0) {
      errors.chordNotation = this.chordValidationIssues;
      control.setErrors(errors);
      return;
    }

    delete errors.chordNotation;
    control.setErrors(Object.keys(errors).length > 0 ? errors : null);
  }

  private async onSaveDialogAfterClosed(save: boolean, url: string) {
    if (save && this.song && !this.form.invalid) {
      const data = this.form.getRawValue() as Partial<Song>;
      await this.songService.update$(this.song.id, data);
    }

    this.form.markAsPristine();
    await this.router.navigateByUrl(url);
  }
}
