import {
  ChangeDetectionStrategy,
  Component,
  computed,
  effect,
  inject,
  input,
  linkedSignal,
  untracked,
} from '@angular/core';
import { FormsModule } from '@angular/forms';
import {
  ReturnProcessChecklistAnswer,
  ReturnProcessChecklistAnswerSchema,
  ReturnProcessChecklistQuestion,
  ReturnProcessStore,
} from '@isa/oms/data-access';
import {
  CheckboxComponent,
  ChecklistComponent,
  CheckboxLabelDirective,
  ChecklistValueDirective,
  TextareaComponent,
} from '@isa/ui/input-controls';
import { isEqual } from 'lodash';

@Component({
  selector: 'oms-feature-return-process-checklist-question',
  templateUrl: './return-process-checklist-question.component.html',
  styleUrls: ['./return-process-checklist-question.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: true,
  imports: [
    FormsModule,
    CheckboxComponent,
    ChecklistComponent,
    ChecklistValueDirective,
    CheckboxLabelDirective,
    TextareaComponent,
  ],
})
export class ReturnProcessChecklistQuestionComponent {
  #returnProcessStore = inject(ReturnProcessStore);

  returnProcessId = input.required<number>();

  question = input.required<ReturnProcessChecklistQuestion>();

  currentAnswer = computed(() => {
    const currentAnswersRaw =
      this.#returnProcessStore.entityMap()[this.returnProcessId()]?.answers[
        this.question().key
      ];

    if (!currentAnswersRaw) {
      return ReturnProcessChecklistAnswerSchema.parse({});
    }

    return ReturnProcessChecklistAnswerSchema.parse(currentAnswersRaw);
  });

  options = linkedSignal(() => this.currentAnswer().options, {
    equal: isEqual,
  });

  other = linkedSignal(() => this.currentAnswer().other, { equal: isEqual });

  valueChangesEffect = effect(() => {
    const options = this.options();
    const other = this.other();
    untracked(() => {
      this.updateAnswer({ options, other });
    });
  });

  updateAnswer(answer: ReturnProcessChecklistAnswer) {
    this.#returnProcessStore.setAnswer(
      this.returnProcessId(),
      this.question().key,
      answer,
    );
  }
}
