import { FormSelectItem } from '@af/digi-ng/_form/form-select';
import {
  ChangeDetectionStrategy,
  Component,
  EventEmitter,
  Input,
  OnChanges,
  Output,
  SimpleChanges,
} from '@angular/core';
import { AbstractControl, FormControl, FormGroup } from '@angular/forms';
import { Organization } from '@msfa-models/organization.model';
import { RequiredValidator } from '@msfa-utils/validators/required.validator';

@Component({
  selector: 'msfa-organization-picker-form',
  templateUrl: './organization-picker-form.component.html',
  styleUrls: ['./organization-picker-form.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class OrganizationPickerFormComponent implements OnChanges {
  @Input() organizations: Array<Organization> | null = null;
  @Input() selectedOrganization: Organization;
  @Input() label = 'Välj organisation';
  @Input() submitText = 'Logga in';
  @Input() compact = false;
  @Output() selectedOrganizationChanged = new EventEmitter<Organization>();

  organizationPickerFormGroup: FormGroup = new FormGroup({
    organization: new FormControl(null, [RequiredValidator('Organisation')]),
  });
  selectableOrganizations: Array<FormSelectItem> = [];

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.selectedOrganization) {
      this.organizationFormControl.patchValue(this.selectedOrganization.organizationNumber);
    }
    if (changes.organizations && this.organizations?.length) {
      this.selectableOrganizations = this.organizations.map(({ name, organizationNumber }) => ({
        name,
        value: organizationNumber,
      }));
    }
  }

  get organizationFormControl(): AbstractControl {
    return this.organizationPickerFormGroup.get('organization');
  }

  onFormSubmitted(): void {
    if (!this.organizationPickerFormGroup) {
      return;
    }

    this.organizationPickerFormGroup.markAllAsTouched();

    if (!this.organizations || this.organizationPickerFormGroup.invalid) {
      return;
    }
    const newOrganization = this.organizations.find(
      organization => organization.organizationNumber === this.organizationFormControl.value
    );

    if (!newOrganization || newOrganization?.organizationNumber === this.selectedOrganization?.organizationNumber) {
      return;
    }

    this.selectedOrganizationChanged.emit(newOrganization);
  }
}
