import React, { useState } from 'react';
import DeleteIcon from '@mui/icons-material/Delete';
import AddIcon from '@mui/icons-material/Add';
import ImageIcon from '@mui/icons-material/Image';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import RadioButtonUncheckedIcon from '@mui/icons-material/RadioButtonUnchecked';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import ExpandLessIcon from '@mui/icons-material/ExpandLess';
import KeyboardDoubleArrowDownIcon from '@mui/icons-material/KeyboardDoubleArrowDown';
import KeyboardDoubleArrowUpIcon from '@mui/icons-material/KeyboardDoubleArrowUp';

import DragIndicatorIcon from '@mui/icons-material/DragIndicator';

interface Answer {
    id: string;
    text: string;
    image_url?: string;
    is_correct: boolean;
}

interface Question {
    id: string;
    question: string;
    description?: string;
    image_url?: string;
    answers: Answer[];
}

interface QuizQuestionEditorProps {
    question: Question;
    questionNumber: number;
    totalQuestions: number;
    questionIndex: number;
    onUpdate: (question: Question) => void;
    onDelete: () => void;
    onMove: (direction: 'up' | 'down') => void;
    canDelete: boolean;
    setModalConfig: (config: any) => void;
    closeModal: () => void;
}

const QuizQuestionEditor: React.FC<QuizQuestionEditorProps> = ({
    question,
    questionNumber,
    totalQuestions,
    questionIndex,
    onUpdate,
    onDelete,
    onMove,
    canDelete,
    setModalConfig,
    closeModal
}) => {
    const [collapsed, setCollapsed] = useState(false);

    const generateId = () => {
        return 'id_' + Math.random().toString(36).substr(2, 9);
    };

    const updateQuestion = (field: keyof Question, value: any) => {
        onUpdate({
            ...question,
            [field]: value,
        });
    };

    const addAnswer = () => {
        const newAnswer: Answer = {
            id: generateId(),
            text: '',
            image_url: '',
            is_correct: false,
        };
        updateQuestion('answers', [...question.answers, newAnswer]);
    };

    const updateAnswer = (answerId: string, field: keyof Answer, value: any) => {
        const updatedAnswers = question.answers.map(answer =>
            answer.id === answerId ? { ...answer, [field]: value } : answer
        );
        updateQuestion('answers', updatedAnswers);
    };

    const deleteAnswer = (answerId: string) => {
        if (question.answers.length <= 2) {
            setModalConfig({
                isOpen: true,
                type: 'toast',
                title: 'Error',
                message: 'A question must have at least 2 answers.',
                position: 'top-right',
                mode: 'error',
            });
            setTimeout(closeModal, 3000);
            return;
        }
        const updatedAnswers = question.answers.filter(answer => answer.id !== answerId);
        updateQuestion('answers', updatedAnswers);
    };

    const setCorrectAnswer = (answerId: string) => {
        const updatedAnswers = question.answers.map(answer => ({
            ...answer,
            is_correct: answer.id === answerId,
        }));
        updateQuestion('answers', updatedAnswers);
    };

    const openMediaUploader = (type: 'question' | 'answer', answerId?: string) => {
        if (typeof (window as any).wp !== 'undefined' && (window as any).wp.media) {
            const mediaUploader = (window as any).wp.media({
                title: 'Select Image',
                button: {
                    text: 'Use Image'
                },
                multiple: false,
                library: {
                    type: 'image'
                }
            });

            mediaUploader.on('select', () => {
                const attachment = mediaUploader.state().get('selection').first().toJSON();
                const imageUrl = attachment.url;

                if (type === 'question') {
                    updateQuestion('image_url', imageUrl);
                } else if (type === 'answer' && answerId) {
                    updateAnswer(answerId, 'image_url', imageUrl);
                }
            });

            mediaUploader.open();
        } else {
            alert('WordPress media uploader is not available.');
        }
    };

    return (
        <div className="question-editor">
            <div className="question-header">
                <div className="question-title">
                    <div className="move-buttons">
                        <button
                            className="move-btn move-up"
                            onClick={() => onMove('up')}
                            disabled={questionIndex === 0}
                            title="Move Up"
                        >
                            <KeyboardDoubleArrowUpIcon className="expand-icon" />
                        </button>
                        <button
                            className="move-btn move-down"
                            onClick={() => onMove('down')}
                            disabled={questionIndex === totalQuestions - 1}
                            title="Move Down"
                        >
                            <KeyboardDoubleArrowDownIcon className="expand-icon" />
                        </button>
                    </div>
                    <h4>Question {questionNumber}</h4>
                    <button
                        className="collapse-btn"
                        onClick={() => setCollapsed(!collapsed)}
                    >
                        {collapsed ? <ExpandLessIcon className="expand-icon" /> : <ExpandMoreIcon className="expand-icon" />}
                    </button>
                </div>
                <div className="question-actions">
                    {canDelete && (
                        <button
                            className="delete-question-btn"
                            onClick={onDelete}
                            title="Delete Question"
                        >
                            <DeleteIcon />
                        </button>
                    )}
                </div>
            </div>

            {!collapsed && (
                <div className="question-content">
                    <div className="form-group">
                        <label>Question Text *</label>
                        <textarea
                            value={question.question}
                            onChange={(e) => updateQuestion('question', e.target.value)}
                            placeholder="Enter your question"
                            rows={2}
                        />
                    </div>

                    <div className="form-group">
                        <label>Description (Optional)</label>
                        <textarea
                            value={question.description || ''}
                            onChange={(e) => updateQuestion('description', e.target.value)}
                            placeholder="Add additional context or instructions"
                            rows={2}
                        />
                    </div>

                    <div className="form-group">
                        <label>Question Image (Optional)</label>
                        <div className="image-upload">
                            {question.image_url ? (
                                <div className="image-preview">
                                    <img src={question.image_url} alt="Question" />
                                    <div className="image-actions">
                                        <button
                                            className="change-image-btn"
                                            onClick={() => openMediaUploader('question')}
                                        >
                                            Change
                                        </button>
                                        <button
                                            className="remove-image-btn"
                                            onClick={() => updateQuestion('image_url', '')}
                                        >
                                            Remove
                                        </button>
                                    </div>
                                </div>
                            ) : (
                                <button
                                    className="upload-image-btn"
                                    onClick={() => openMediaUploader('question')}
                                >
                                    <ImageIcon />
                                    Upload Image
                                </button>
                            )}
                        </div>
                    </div>

                    <div className="answers-section">
                        <div className="answers-header">
                            <label>Answers *</label>
                            <button className="add-answer-btn" onClick={addAnswer}>
                                <AddIcon />
                                Add Answer
                            </button>
                        </div>

                        <div className="answers-list">
                            {question.answers.map((answer, index) => (
                                <div key={answer.id} className="answer-item">
                                    <div className="answer-header">
                                        <button
                                            className={`correct-answer-btn ${answer.is_correct ? 'correct' : ''
                                                }`}
                                            onClick={() => setCorrectAnswer(answer.id)}
                                            title={answer.is_correct ? 'Correct answer' : 'Mark as correct'}
                                        >
                                            {answer.is_correct ? (
                                                <CheckCircleIcon />
                                            ) : (
                                                <RadioButtonUncheckedIcon />
                                            )}
                                        </button>
                                        <span className="answer-label">Answer {index + 1}</span>
                                        {question.answers.length > 2 && (
                                            <button
                                                className="delete-answer-btn"
                                                onClick={() => deleteAnswer(answer.id)}
                                                title="Delete Answer"
                                            >
                                                <DeleteIcon />
                                            </button>
                                        )}
                                    </div>

                                    <div className="answer-content">
                                        <input
                                            type="text"
                                            value={answer.text}
                                            onChange={(e) => updateAnswer(answer.id, 'text', e.target.value)}
                                            placeholder={`Answer ${index + 1}`}
                                        />

                                        <div className="answer-image">
                                            {answer.image_url ? (
                                                <div className="answer-image-preview">
                                                    <img src={answer.image_url} alt={`Answer ${index + 1}`} />
                                                    <button
                                                        className="remove-answer-image-btn"
                                                        onClick={() => updateAnswer(answer.id, 'image_url', '')}
                                                        title="Remove image"
                                                    >
                                                        ×
                                                    </button>
                                                </div>
                                            ) : (
                                                <button
                                                    className="add-answer-image-btn"
                                                    onClick={() => openMediaUploader('answer', answer.id)}
                                                    title="Add image"
                                                >
                                                    <ImageIcon />
                                                </button>
                                            )}
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                        <small className="answers-hint">
                            Click the circle icon to mark the correct answer
                        </small>
                    </div>
                </div>
            )}
        </div>
    );
};

export default QuizQuestionEditor;
