import { ChangeDetectionStrategy, Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { AbstractControl, FormControl, FormGroup } from '@angular/forms';
import { markControlsAsDirty } from '@msfa-utils/mark-controls-as-dirty.util';
import { RequiredValidator } from '@msfa-validators/required.validator';
import { BehaviorSubject } from 'rxjs';

export interface SlutredovisningStep2FormData {
  progressDescription: string;
  nextStepDescription: string;
  otherInformation: string;
}

type FormControlNames = keyof SlutredovisningStep2FormData;

@Component({
  selector: 'msfa-slutredovisning-form-step2',
  templateUrl: './slutredovisning-form-step2.component.html',
  styleUrls: ['./slutredovisning-form-step2.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SlutredovisningFormStep2Component implements OnInit {
  readonly framstegFormName: FormControlNames = 'progressDescription';
  readonly nastaStegFormName: FormControlNames = 'nextStepDescription';
  readonly ovrigtFormName: FormControlNames = 'otherInformation';
  shouldValidate$ = new BehaviorSubject<boolean>(false);
  @Output() nextClick = new EventEmitter<SlutredovisningStep2FormData>();
  @Output() backClick = new EventEmitter<void>();
  @Input() formGroup: FormGroup;
  @Input() genomforandereferens: number;

  formControlIsInvalid(formControl: AbstractControl): boolean {
    return formControl.invalid && (formControl.touched || this.shouldValidate$.value);
  }

  get framstegFormControl(): FormControl {
    return this.formGroup.get(this.framstegFormName) as FormControl;
  }
  get nastaStegFormControl(): FormControl {
    return this.formGroup.get(this.nastaStegFormName) as FormControl;
  }
  get ovrigtFormControl(): FormControl {
    return this.formGroup.get(this.ovrigtFormName) as FormControl;
  }

  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);
    }
  }

  ngOnInit(): void {
    if (!this.framstegFormControl) {
      this.formGroup.addControl(this.framstegFormName, new FormControl(null, RequiredValidator()));
      this.formGroup.addControl(this.nastaStegFormName, new FormControl(null, RequiredValidator()));
      this.formGroup.addControl(this.ovrigtFormName, new FormControl(''));
    }
  }

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