import { ChangeDetectionStrategy, Component, computed, input, OnInit, output, signal, } from '@angular/core'; import { AsyncPipe } from '@angular/common'; import { injectMutation } from '@tanstack/angular-query-experimental'; import { Observable, tap } 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, imports: [AsyncPipe, SurveyQuestionComponent, ButtonDirective], providers: [SurveyService], }) export class SurveyModalComponent implements OnInit { private surveyServ = injectSurveyService(); private uiServ = injectUIService(); closeModal = output(); survey = input.required(); survey$!: Observable; questionsLength = 0; answers = signal([]); valid = computed(() => this.answers().every((answer) => answer.answer_id !== 0)); save = injectMutation(() => ({ mutationFn: (_: void) => this.surveyServ.saveSurvey(this.survey(), 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), })); ngOnInit(): void { this.survey$ = this.surveyServ.getSurvey(this.survey()).pipe( tap((questions) => { this.questionsLength = questions.length; this.answers.set([...Array(questions.length)].map(() => ({ answer_id: 0 }))); }) ); } addAnswer(answer: AnswerDto, questionIdx: number) { const answers = [...this.answers()]; answers[questionIdx] = answer; this.answers.set(answers); } }