import {
  ChangeDetectionStrategy,
  Component,
  effect,
  inject,
  input,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import {
  ReturnProcessSelectQuestion,
  ReturnProcessStore,
} from '@isa/oms/data-access';
import { ChipsComponent, ChipOptionComponent } from '@isa/ui/input-controls';

@Component({
  selector: 'oms-feature-return-process-select-question',
  templateUrl: './return-process-select-question.component.html',
  styleUrls: ['./return-process-select-question.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: true,
  imports: [ChipsComponent, ChipOptionComponent, ReactiveFormsModule],
})
export class ReturnProcessSelectQuestionComponent {
  #returnProcessStore = inject(ReturnProcessStore);

  returnProcessId = input.required<number>();

  question = input.required<ReturnProcessSelectQuestion>();

  control = new FormControl<string | undefined>(undefined, [
    Validators.required,
  ]);

  constructor() {
    this.control.valueChanges.pipe(takeUntilDestroyed()).subscribe((value) => {
      if (this.control.valid) {
        this.#returnProcessStore.setAnswer(
          this.returnProcessId(),
          this.question().key,
          value,
        );
      } else {
        this.#returnProcessStore.removeAnswer(
          this.returnProcessId(),
          this.question().key,
        );
      }
    });

    effect(() => {
      const value =
        this.#returnProcessStore.entityMap()[this.returnProcessId()]?.answers[
          this.question().key
        ];
      if (value !== this.control.value) {
        this.control.setValue(value as string);
      }
    });
  }
}
