import SurveyInfo from "../SurveyInfo/SurveyInfo.tsx";
import QuestionsList, {Question} from "../QuestionsList/QuestionsList.tsx";
import {useEffect, useState} from "react";
import styles from './CompletingSurvey.module.css'
import {useNavigate, useParams} from "react-router-dom";
import {getSurveyById, ISurvey} from "../../api/SurveyApi.ts";
import {getListQuestions} from "../../api/QuestionApi.ts";
import {getAnswerVariants, IAnswerVariant} from "../../api/AnswerVariantsApi.ts";
import {addNewCompletion} from "../../api/CompletionApi.ts";

interface ISelectedAnswers{
    questionId: number;
    answerText: string;
}

export const CompletingSurvey = () => {
    const {surveyId} = useParams<{surveyId: string}>();
    const [survey, setSurvey] = useState<ISurvey | null>(null);
    const [questions, setQuestions] = useState<Question[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    const [selectedAnswers, setSelectedAnswers] = useState<ISelectedAnswers[]>([]);
    const navigate = useNavigate();

    useEffect(() => {
        const fetchSurveyData = async () => {
            try {
                setLoading(true);
                if (!surveyId) return;

                const surveyData = await getSurveyById(parseInt(surveyId));
                setSurvey(surveyData);

                const questionsData = await getListQuestions(parseInt(surveyId));
                const formattedQuestions = await Promise.all(questionsData.map(async q => {
                    const answerVariants = await getAnswerVariants(parseInt(surveyId), q.id);
                    return {
                        id: q.id,
                        text: q.title,
                        questionType: q.questionType as 'SingleAnswerQuestion' | 'MultipleAnswerQuestion',
                        answerVariants: answerVariants.map((a: IAnswerVariant) => ({
                            id: a.id,
                            text: a.text
                        }))
                    };
                }));
                setQuestions(formattedQuestions);
            } catch (error) {
                console.error('Ошибка загрузки опроса:', error);
                setError('Не удалось загрузить опрос');
            } finally {
                setLoading(false);
            }
        };

        fetchSurveyData();
    }, [surveyId]);

    const handleAnswerSelect = (questionId: number, answerText: string) => {
        setSelectedAnswers(prev => {
            const question = questions.find(q => q.id === questionId);
            if (question?.questionType === 'SingleAnswerQuestion') {
                return [
                    ...prev.filter(a => a.questionId !== questionId),
                    { questionId, answerText }
                ];
            }

            const existingAnswerIndex = prev.findIndex(
                a => a.questionId === questionId && a.answerText === answerText
            );

            if (existingAnswerIndex >= 0) {
                return prev.filter((_, index) => index !== existingAnswerIndex);
            } else {
                return [...prev, { questionId, answerText }];
            }
        });
    };

    const handleSubmit = async () => {
        if (!surveyId) return;

        try {
            await addNewCompletion(parseInt(surveyId), {
                answers: selectedAnswers
            });

            navigate('/my-surveys');
        } catch (error) {
            console.error('Ошибка при отправке ответов:', error);
        }
    };

    if (loading) return <div>Загрузка...</div>;
    if (error) return <div>{error}</div>;
    if (!survey) return <div>Опрос не найден</div>;


    return (
        <div className={styles.survey}>
            <SurveyInfo
                titleSurvey={survey.title}
                descriptionSurvey={survey.description}
                setDescriptionSurvey={(value) => setSurvey({ ...survey, description: value })}
                setTitleSurvey={(value) => setSurvey({ ...survey, title: value })}
            />
            <QuestionsList
                questions={questions}
                setQuestions={setQuestions}
                onAnswerSelect={handleAnswerSelect}
            />
            <button className={styles.departur_button} onClick={handleSubmit} disabled={selectedAnswers.length === 0}>Отправить</button>
        </div>
    )
}

export default CompletingSurvey