import { ChangeDetectionStrategy, Component, computed, input, output, signal, } from '@angular/core'; import { toObservable, toSignal } from '@angular/core/rxjs-interop'; import { injectMutation } from '@tanstack/angular-query-experimental'; import { filter, tap, switchMap } from 'rxjs'; import { injectUIService } from '@/core/services/ui.service'; import { ButtonDirective } from '@/shared/ui/button.directive'; import { SurveyQuestionComponent } from '../survey-question/survey-question.component'; import { AnswerDto, Question } from '../survey.models'; import { injectSurveyService, SurveyService } from '../survey.service'; @Component({ selector: 'app-survey-modal', templateUrl: './survey-modal.component.html', styleUrls: ['./survey-modal.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, providers: [SurveyService], imports: [ButtonDirective, SurveyQuestionComponent], }) export class SurveyModalComponent { private surveyServ = injectSurveyService(); private uiServ = injectUIService(); closeModal = output(); survey = input(null); questionsLength = 0; answers = signal([]); survey$ = toObservable(this.survey).pipe( filter((survey): survey is number => survey !== null), switchMap((survey) => this.surveyServ.getSurvey(survey)), tap((questions) => { this.questionsLength = questions.length; this.answers.set([...Array(questions.length)].map(() => ({ answer_id: 0 }))); }) ); surveyQuestions = toSignal(this.survey$, { initialValue: [] as Question[] }); valid = computed(() => this.answers().every((answer) => answer.answer_id !== 0)); save = injectMutation(() => ({ mutationFn: (_: void) => this.surveyServ.saveSurvey(this.survey() ?? 0, this.answers()), onSuccess: (message) => { this.uiServ.showSuccessAlert(message); this.closeModal.emit(); this.uiServ.showToast('¡Tu pregunta ha sido enviada!'); }, onError: (error) => this.uiServ.showErrorAlert(error.message), })); addAnswer(answer: AnswerDto, questionIdx: number) { const answers = this.answers(); answers[questionIdx] = answer; this.answers.set([...answers]); } }