import React, { useState } from 'react' import { motion } from 'framer-motion' import { FaTimes } from 'react-icons/fa' import { SurveyAnswerDto, SurveyDto, SurveyQuestionDto } from '@/proxy/intranet/models' interface SurveyModalProps { survey: SurveyDto onClose: () => void onSubmit: (answers: SurveyAnswerDto[]) => void } import { useLocalization } from '@/utils/hooks/useLocalization' const SurveyModal: React.FC = ({ survey, onClose, onSubmit }) => { const { translate } = useLocalization(); const isUpdate = !!survey.myResponse const [answers, setAnswers] = useState<{ [questionId: string]: any }>(() => { if (survey.myResponse?.answers) { return Object.fromEntries( survey.myResponse.answers.map((a) => [ a.questionId, a.questionType === 'rating' ? Number(a.value) : a.value, ]) ) } return {} }) const [errors, setErrors] = useState<{ [questionId: string]: string }>({}) const handleAnswerChange = (questionId: string, value: any) => { setAnswers((prev) => ({ ...prev, [questionId]: value, })) // Clear error when user provides an answer if (errors[questionId]) { setErrors((prev) => ({ ...prev, [questionId]: '', })) } } const validateAnswers = (): boolean => { const newErrors: { [questionId: string]: string } = {} survey.questions.forEach((question) => { if (question.isRequired) { const val = answers[question.id] const isEmpty = val === undefined || val === null || val === '' || (question.type === 'rating' && Number(val) === 0) if (isEmpty) { newErrors[question.id] = translate('::App.Platform.Intranet.SurveyModal.RequiredField') } } }) setErrors(newErrors) return Object.keys(newErrors).length === 0 } const handleSubmit = (e: React.FormEvent) => { e.preventDefault() if (!validateAnswers()) { return } const surveyAnswers: SurveyAnswerDto[] = survey.questions.map((question) => ({ questionId: question.id, questionType: question.type, value: answers[question.id] || (question.type === 'multiple-choice' ? '' : question.type === 'rating' ? 0 : ''), })) onSubmit(surveyAnswers) } const renderQuestion = (question: SurveyQuestionDto, index: number) => { const questionNumber = index + 1 const hasError = !!errors[question.id] switch (question.type) { case 'rating': return (
{[1, 2, 3, 4, 5].map((star) => ( ))}
{hasError && (

{errors[question.id]}

)}
) case 'multiple-choice': return (
{question.options?.map((option) => ( ))}
{hasError && (

{errors[question.id]}

)}
) case 'yes-no': return (
{['yes', 'no'].map((value) => ( ))}
{hasError && (

{errors[question.id]}

)}
) case 'text': return (
handleAnswerChange(question.id, e.target.value)} className={`w-full px-4 py-2 border rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 ${ hasError ? 'border-red-500' : 'border-gray-300 dark:border-gray-600' }`} placeholder={translate('::App.Platform.Intranet.SurveyModal.AnswerPlaceholder')} /> {hasError && (

{errors[question.id]}

)}
) case 'textarea': return (