import React, {useState, useRef, useEffect} from "react";
import AnswerOption from '../AnswerOption/AnswerOption';
import AddAnswerButton from "../AddAnswerButton/AddAnswerButton.tsx";
import TypeDropdown from "../TypeDropdown/TypeDropdown.tsx";
import styles from './QuestionItem.module.css'


interface QuestionItemProps {
    indexQuestion: number;
    initialTextQuestion?: string;
    valueQuestion: string;
    onChangeQuestion: (valueQuestion: string) => void;
}

const QuestionItem: React.FC<QuestionItemProps> = ({indexQuestion, initialTextQuestion = `Вопрос ${indexQuestion}`,
                                                       valueQuestion, onChangeQuestion}) => {
    const [selectedType, setSelectedType] = useState<'single' | 'multiply'>('single');
    const [answerOption, setAnswerOption] = useState(['']);
    const [textQuestion, setTextQuestion] = useState(initialTextQuestion);
    const [isEditingQuestion, setIsEditingQuestion] = useState(false);

    const textareaQuestionRef = useRef<HTMLTextAreaElement>(null);

    const handleTypeChange = (type: 'single' | 'multiply') => {
        setSelectedType(type);
    }

    const handleAddAnswer = () => {
        setAnswerOption([...answerOption, '']);
    };

    const handleQuestionClick = () => {
        setIsEditingQuestion(true);
    }

    const handleTextareaQuestionChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
        setTextQuestion(event.target.value);
    }

    const handleSaveQuestion = () => {
        setIsEditingQuestion(false);
        onChangeQuestion(textQuestion);
    }

    const handleQuestionKeyDown = (keyDownEvent: React.KeyboardEvent<HTMLTextAreaElement>) => {
        if (keyDownEvent.key === 'Enter') {
            keyDownEvent.preventDefault();
            handleSaveQuestion()
        }
    }

    const handleQuestionBlur = () => {
        handleSaveQuestion()
    }

    useEffect(() => {
        if (isEditingQuestion && textareaQuestionRef.current) {
            textareaQuestionRef.current.focus();
        }
    }, [isEditingQuestion]);

    const handleAnswerChange = (index: number, value: string) => {
        const newAnswerOption = [...answerOption];
        newAnswerOption[index] = value;
        setAnswerOption(newAnswerOption);
    }

    useEffect(() => {
        setTextQuestion(valueQuestion);
    }, [valueQuestion]);

    return (
        <div className={styles.questionCard}>
            <div className={styles.questionContainer}>
                {isEditingQuestion ? (
                    <textarea
                        className={styles.questionTextarea}
                        ref={textareaQuestionRef}
                        value={textQuestion === initialTextQuestion ? '' : textQuestion}
                        onChange={handleTextareaQuestionChange}
                        onKeyDown={handleQuestionKeyDown}
                        onBlur={handleQuestionBlur}
                        placeholder={initialTextQuestion}
                    />
                ) : (
                    <button className={styles.buttonQuestion} onClick={handleQuestionClick}>
                        <h2 className={styles.textQuestion}>{textQuestion || initialTextQuestion}</h2>
                    </button>
                )}
                {answerOption.map((answerText, index) => (
                    <AnswerOption
                        key={index}
                        selectedType={selectedType}
                        index={index + 1} // Индекс ответа
                        value={answerText}
                        onChange={(value) => handleAnswerChange(index, value)}
                    />
                ))}

                <AddAnswerButton
                    onClick={handleAddAnswer}
                />
            </div>
            <TypeDropdown selectedType={selectedType} onTypeChange={handleTypeChange}/>
        </div>
    );
}

export default QuestionItem;