import { RadiobuttonModel } from '@af/digi-ng/_form/form-radiobutton-group';
import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core';
import { FormArray, FormControl, FormGroup } from '@angular/forms';
import { Anstallningsform, MainOccupation, Omfattning } from '@msfa-models/slutredovisning.model';
import { Yrkesgrupp } from '@msfa-models/yrkesgrupp.model';
import { Yrkesomrade } from '@msfa-models/yrkesomrade.model';
import { capitalizeSentence } from '@msfa-utils/capitalize-sentence.util';
import { ErrorLink } from '@ui/error-list/error-link.model';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { SlutredovisningFormService } from '../../slutredovisning-form.service';
import { SlutredovisningFormStep0WorkFormData } from './slutredovisning-form-step0-work.model';
import { SlutredovisningFormStep0WorkValidator } from './slutredovisning-form-step0-work.validator';
import { UiIconType } from '@ui/icon/icon-type.enum';
import { UiIconSize } from '@ui/icon/icon-size.enum';

@Component({
  selector: 'msfa-slutredovisning-form-step0-work',
  templateUrl: './slutredovisning-form-step0-work.component.html',
  styleUrls: ['./slutredovisning-form-step0-work.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SlutredovisningFormStep0WorkComponent implements OnInit {
  readonly formGroupKey: MainOccupation = MainOccupation.Work;
  readonly UiIconType = UiIconType;
  readonly UiIconSize = UiIconSize;
  @Input() formGroupRef: FormGroup;
  @Input() formData: SlutredovisningFormStep0WorkFormData;
  @Input() shouldValidate: boolean;
  MainOccupation = MainOccupation;
  Anstallningsform = Anstallningsform;
  Omfattning = Omfattning;

  yrkesomradeSelectOptions$: Observable<Yrkesomrade[]> = this.slutredovisningFormService.yrkesomraden$;
  formArray: FormArray;

  anstallningsformOptions: RadiobuttonModel[] = Object.values(Anstallningsform).map(value => ({
    label: capitalizeSentence(value),
    value,
  }));
  omfattningOptions: RadiobuttonModel[] = Object.values(Omfattning).map(value => ({
    label: capitalizeSentence(value),
    value,
  }));

  constructor(private slutredovisningFormService: SlutredovisningFormService) {}

  getYrkesgruppSelectOptions$(index: number): Observable<Yrkesgrupp[]> {
    const yrkesomradeId = this.formArray.controls[index].get('yrkesomrade').value as string;

    return this.yrkesomradeSelectOptions$.pipe(
      map(yrkesomraden =>
        yrkesomradeId
          ? yrkesomraden
              .filter(yo => yo.value === yrkesomradeId)
              .reduce((yrkesgrupper: Yrkesgrupp[], yo: Yrkesomrade) => {
                yrkesgrupper.push(...yo.items);
                return yrkesgrupper;
              }, [])
          : null
      )
    );
  }

  get errorListErrors(): ErrorLink[] {
    const formControlErrors: ErrorLink[] = [];
    if (this.shouldValidate) {
      this.formArray.controls.forEach(arrayControl => {
        if (arrayControl.errors) {
          Object.entries(arrayControl.errors).forEach(([key, value]) => {
            formControlErrors.push({
              elementId: `slutredovisning-${key}-control`,
              text: value as string,
            });
          });
        }
      });
    }
    return formControlErrors;
  }

  formControlIsInvalid(formControlName: string, index: number): boolean {
    const errors = this.formArray.controls[index].errors;
    return errors && errors[formControlName] && this.shouldValidate;
  }

  formControlError(formControlName: string, index: number): string {
    const errors = this.formArray.controls[index].errors;
    return errors && (errors[formControlName] as string);
  }

  addNewFormGroupToFormArray(): void {
    this.formArray.push(
      new FormGroup(
        {
          yrkesomrade: new FormControl(null),
          yrkesgrupp: new FormControl(null),
          anstallningsform: new FormControl(null),
          annatAnstallningComment: new FormControl(null),
          omfattning: new FormControl(null),
          omfattningPercent: new FormControl(null),
        },
        [SlutredovisningFormStep0WorkValidator.slutredovisningFormStep0WorkIsValid()]
      )
    );
  }

  removeGroup(index: number): void {
    this.formArray.removeAt(index);
  }

  ngOnInit(): void {
    if (this.formGroupRef.get(this.formGroupKey)) {
      this.formArray = this.formGroupRef.get(this.formGroupKey) as FormArray;
    } else {
      this.formArray = new FormArray([]);
      this.addNewFormGroupToFormArray();
      this.formGroupRef.addControl(this.formGroupKey, this.formArray);
    }
  }
}
