import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { AbstractControl, FormControl, FormGroup } from '@angular/forms';
import { RequiredValidator } from '@msfa-validators/required.validator';
import { MainOccupation } from '@msfa-models/slutredovisning.model';

export interface SlutredovisningFormStep0OtherFormData {
  otherExplanation: string;
}

type FormKeys = keyof SlutredovisningFormStep0OtherFormData;

@Component({
  selector: 'msfa-slutredovisning-form-step0-other',
  templateUrl: './slutredovisning-form-step0-other.component.html',
  styleUrls: ['./slutredovisning-form-step0-other.component.scss'],
})
export class SlutredovisningFormStep0OtherComponent implements OnInit {
  readonly formGroupKey: MainOccupation = MainOccupation.Other;
  @Input() formGroupRef: FormGroup;

  @Input() formData: SlutredovisningFormStep0OtherFormData;
  @Input() shouldValidate: boolean;
  @Output() nextClick = new EventEmitter<SlutredovisningFormStep0OtherFormData>();
  @Output() backClick = new EventEmitter<void>();

  private otherExplanationFormControlName: FormKeys = 'otherExplanation';

  formGroup: FormGroup | AbstractControl;

  get otherExplanationFormControl(): AbstractControl | undefined {
    return this.formGroup.get(this.otherExplanationFormControlName);
  }

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

  ngOnInit(): void {
    if (this.formGroupRef.get(this.formGroupKey)) {
      this.formGroup = this.formGroupRef.get(this.formGroupKey);
    } else {
      this.formGroup = new FormGroup({
        [this.otherExplanationFormControlName]: new FormControl(
          null,
          RequiredValidator('En beskrivning av Annat är obligatoriskt.')
        ),
      });
      this.formGroupRef.addControl(this.formGroupKey, this.formGroup);
    }
  }
}
