import { ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { AbstractControl, FormArray, FormControl, FormGroup } from '@angular/forms';
import { BehaviorSubject } from 'rxjs';
import { markControlsAsDirty } from '@msfa-utils/mark-controls-as-dirty.util';
import { Activity } from '@msfa-models/activity.model';
import { SlutredovisningFormService } from '../slutredovisning-form.service';
import { take } from 'rxjs/operators';
import { RequiredValidator } from '@msfa-validators/required.validator';

export interface SlutredovisningStep1FormData {
  activities: { whatHasBeenDone: string; id: string; name: string }[];
}

type FormControlNames = keyof SlutredovisningStep1FormData;

@Component({
  selector: 'msfa-slutredovisning-form-step1',
  templateUrl: './slutredovisning-form-step1.component.html',
  styleUrls: ['./slutredovisning-form-step1.component.scss'],
})
export class SlutredovisningFormStep1Component implements OnInit {
  readonly ACTIVITES_FORM_NAME: FormControlNames = 'activities';
  shouldValidate$ = new BehaviorSubject<boolean>(false);
  @Output() nextClick = new EventEmitter<SlutredovisningStep1FormData>();
  @Output() backClick = new EventEmitter<void>();
  @Input() genomforandereferens: number;
  @Input() formGroup: FormGroup;

  constructor(
    private slutredovisningFormService: SlutredovisningFormService,
    private changeDetectionRef: ChangeDetectorRef
  ) {}

  private clearActivities(): void {
    this.activitiesFormArray.clear();
  }

  private addActivityToForm(activity: Activity): void {
    this.activitiesFormArray.push(
      new FormGroup({
        name: new FormControl(activity.name),
        id: new FormControl(activity.id),
        whatHasBeenDone: new FormControl(null, RequiredValidator('Beskrivning är obligatorisk')),
      })
    );
    this.changeDetectionRef.detectChanges();
  }

  ngOnInit(): void {
    if (!this.activitiesFormArray) {
      this.formGroup.addControl(this.ACTIVITES_FORM_NAME, new FormArray([]));

      this.slutredovisningFormService
        .getAllChosenActivities(this.genomforandereferens)
        .pipe(take(1))
        .subscribe(activities => {
          this.clearActivities();
          activities.forEach(activity => this.addActivityToForm(activity));
        });
    }
  }
  formControlIsInvalid(formControl: AbstractControl): boolean {
    return formControl.invalid && (formControl.touched || this.shouldValidate$.value);
  }

  get activitiesFormArray(): FormArray {
    return this.formGroup.get(this.ACTIVITES_FORM_NAME) as FormArray;
  }

  verifyAndEmitData(): void {
    this.shouldValidate$.next(true);
    markControlsAsDirty(Object.values(this.formGroup.controls));
    this.formGroup.markAllAsTouched();

    if (this.formGroup.valid) {
      this.nextClick.emit(this.formGroup.value);
    }
  }

  goBack(): void {
    this.backClick.emit();
  }
}
