import React, { useState } from "react";
import QuestionItem from "../QuestionItem/QuestionItem.tsx";
import AddQuestionButton from "../AddQuestionButton/AddQuestionButton.tsx";

interface QuestionsListProps {}

interface Question {
    id: number;
    text: string;
}

const QuestionsList: React.FC<QuestionsListProps> = () => {
    const [questions, setQuestions] = useState<Question[]>([
        { id: 1, text: '' },
    ]);

    const handleAddQuestion = () => {
        const maxId = questions.reduce((max, question) => Math.max(max, question.id), 0);
        const newQuestion: Question = {
            id: maxId + 1,
            text: ''
        };
        setQuestions([...questions, newQuestion]);
    };

    const handleQuestionChange = (id: number, value: string) => {
        const newQuestions = questions.map((question) =>
            question.id === id ? { ...question, text: value } : question
        );
        setQuestions(newQuestions);
    };

    const handleDeleteQuestion = (id: number) => {
        const newQuestions = questions.filter((question) => question.id !== id);
        setQuestions(newQuestions);
    };

    return (
        <>
            {questions.map((question) => (
                <QuestionItem
                    key={question.id}
                    indexQuestion={question.id}
                    valueQuestion={question.text}
                    onDeleteQuestion={() => handleDeleteQuestion(question.id)}
                    onChangeQuestion={(value) => handleQuestionChange(question.id, value)}
                />
            ))}
            <AddQuestionButton onClick={handleAddQuestion} />
        </>
    );
};

export default QuestionsList;
