import { SelectOption } from '@ui/select/select-option.model';
import {
  ChangeDetectionStrategy,
  Component,
  EventEmitter,
  Input,
  OnChanges,
  Output,
  SimpleChanges,
} from '@angular/core';
import { AbstractControl, FormControl, FormGroup } from '@angular/forms';
import { Handledare } from '@msfa-models/handledare.model';
import { HandledareService } from '@msfa-services/handledare.service';
import { RequiredValidator } from '@msfa-utils/validators/required.validator';
import { Observable } from 'rxjs';

@Component({
  selector: 'msfa-handledare-picker-form',
  templateUrl: './handledare-picker-form.component.html',
  styleUrls: ['./handledare-picker-form.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class HandledarePickerFormComponent implements OnChanges {
  @Input() selectedHandledareId: string;
  @Input() handledare: Handledare[];
  @Input() avropIds: string[];
  @Input() label = 'Välj handledare';
  @Input() submitText = 'Spara handledare';
  @Input() skipSubmit = false;
  @Input() invalid = false;
  @Output() selectedHandledareChanged = new EventEmitter<string>();
  formGroup: FormGroup = new FormGroup({
    handledare: new FormControl(null, [RequiredValidator('Handledare är obligatorisk')]),
  });
  selectableHandledare: SelectOption[] = [];
  submitted = false;
  lastSavedHandledare$: Observable<Handledare> = this.handledareService.lastSavedHandledare$;
  submitHandledareLoading$: Observable<boolean> = this.handledareService.submitHandledareLoading$;

  constructor(private handledareService: HandledareService) {}

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.selectedHandledareId) {
      this.handledareFormControl.patchValue(this.selectedHandledareId);
    }
    if (changes.handledare && this.handledare?.length) {
      this.selectableHandledare = this.handledare.map(({ ciamUserId, fullName }) => ({
        name: fullName,
        value: ciamUserId,
      }));
    }
  }

  get handledareFormControl(): AbstractControl {
    return this.formGroup.get('handledare');
  }

  handledareChanged(): void {
    this.submitted = false;
    this.selectedHandledareChanged.emit(this.handledareFormControl.value);
  }

  onFormSubmitted(): void {
    this.submitted = true;
    this.formGroup.markAllAsTouched();

    if (this.formGroup.invalid || this.handledareFormControl.value === this.selectedHandledareId) {
      return;
    }

    const newHandledare = this.handledare.find(
      handledare => handledare.ciamUserId === this.handledareFormControl.value
    );

    this.handledareService.assignHandledare(this.avropIds, newHandledare);
  }
}
