import React, { useState } from 'react';
import AddIcon from '@mui/icons-material/Add';
import DeleteIcon from '@mui/icons-material/Delete';
import DragIndicatorIcon from '@mui/icons-material/DragIndicator';
import NoticeModal from './../NoticeModal/NoticeModal';

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

interface Question {
    id: string;
    text: string;
    description?: string;
    answers: Answer[];
    required: boolean;
    allow_multiple: boolean;
}

interface QuestionEditorProps {
    questions: Question[];
    onUpdate: (questions: Question[]) => void;
}

const QuestionEditor: React.FC<QuestionEditorProps> = ({ questions, onUpdate }) => {
    const [modalConfig, setModalConfig] = useState({
        isOpen: false,
        type: 'toast' as 'success' | 'error' | 'confirmation' | 'premium' | 'toast',
        title: '',
        message: '',
        position: 'top-right' as 'top-right' | 'center',
        mode: 'success' as 'success' | 'error',
        onConfirm: () => { },
        onClose: () => { },
        confirmText: 'OK',
        declineText: 'Cancel'
    });

    const closeModal = () => {
        setModalConfig(prev => ({ ...prev, isOpen: false }));
    };

    const showErrorModal = (message: string) => {
        setModalConfig({
            isOpen: true,
            type: 'toast',
            title: 'Error',
            message: message,
            position: 'top-right',
            mode: 'error',
            onConfirm: closeModal,
            onClose: closeModal,
            confirmText: 'OK',
            declineText: 'Cancel'
        });
    };

    const generateId = () => `id_${Math.random().toString(36).substring(2, 11)}`;

    const addQuestion = () => {
        const newQuestion: Question = {
            id: generateId(),
            text: '',
            description: '',
            answers: [
                { id: generateId(), text: '', image_url: '' },
                { id: generateId(), text: '', image_url: '' }
            ],
            required: true,
            allow_multiple: false
        };
        onUpdate([...questions, newQuestion]);
    };

    const updateQuestion = (questionId: string, field: keyof Question, value: any) => {
        const updatedQuestions = questions.map(q => 
            q.id === questionId ? { ...q, [field]: value } : q
        );
        onUpdate(updatedQuestions);
    };

    const deleteQuestion = (questionId: string) => {
        if (questions.length <= 1) {
            showErrorModal('You must have at least one question.');
            return;
        }
        const updatedQuestions = questions.filter(q => q.id !== questionId);
        onUpdate(updatedQuestions);
    };

    const addAnswer = (questionId: string) => {
        const updatedQuestions = questions.map(q => {
            if (q.id === questionId) {
                const newAnswer: Answer = {
                    id: generateId(),
                    text: '',
                    image_url: ''
                };
                return { ...q, answers: [...q.answers, newAnswer] };
            }
            return q;
        });
        onUpdate(updatedQuestions);
    };

    const updateAnswer = (questionId: string, answerId: string, field: keyof Answer, value: string) => {
        const updatedQuestions = questions.map(q => {
            if (q.id === questionId) {
                const updatedAnswers = q.answers.map(a => 
                    a.id === answerId ? { ...a, [field]: value } : a
                );
                return { ...q, answers: updatedAnswers };
            }
            return q;
        });
        onUpdate(updatedQuestions);
    };

    const deleteAnswer = (questionId: string, answerId: string) => {
        const question = questions.find(q => q.id === questionId);
        if (question && question.answers.length <= 2) {
            showErrorModal('Each question must have at least 2 answers.');
            return;
        }

        const updatedQuestions = questions.map(q => {
            if (q.id === questionId) {
                const updatedAnswers = q.answers.filter(a => a.id !== answerId);
                return { ...q, answers: updatedAnswers };
            }
            return q;
        });
        onUpdate(updatedQuestions);
    };

    return (
        <div className="question-editor">
            <div className="editor-info">
                <p><strong>Survey Structure:</strong> Poll Title → Question 1 → Question 2 → etc.</p>
                <p><small>Each question below will be presented separately to users after they see your poll title and description.</small></p>
            </div>
            
            <div className="questions-list">
                {questions.map((question, questionIndex) => (
                    <div key={question.id} className="question-item">
                        <div className="question-header">
                            <div className="question-drag-handle">
                                <DragIndicatorIcon />
                            </div>
                            <h4>Question {questionIndex + 1}</h4>
                            <div className="question-actions">
                                <button
                                    type="button"
                                    className="delete-question-btn"
                                    onClick={() => deleteQuestion(question.id)}
                                    disabled={questions.length <= 1}
                                >
                                    <DeleteIcon />
                                </button>
                            </div>
                        </div>

                        <div className="question-content">
                            <div className="form-group">
                                <label>Question Text *</label>
                                <input
                                    type="text"
                                    value={question.text}
                                    onChange={(e) => updateQuestion(question.id, 'text', e.target.value)}
                                    placeholder="Enter your question..."
                                />
                            </div>

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

                            <div className="question-settings">
                                <div className="form-group checkbox-group">
                                    <label>
                                        <input
                                            type="checkbox"
                                            checked={question.required}
                                            onChange={(e) => updateQuestion(question.id, 'required', e.target.checked)}
                                        />
                                        Required question
                                    </label>
                                </div>

                                <div className="form-group checkbox-group">
                                    <label>
                                        <input
                                            type="checkbox"
                                            checked={question.allow_multiple}
                                            onChange={(e) => updateQuestion(question.id, 'allow_multiple', e.target.checked)}
                                        />
                                        Allow multiple answers
                                    </label>
                                </div>
                            </div>

                            <div className="answers-section">
                                <h5>Answer Options</h5>
                                <div className="answers-list">
                                    {question.answers.map((answer, answerIndex) => (
                                        <div key={answer.id} className="answer-item">
                                            <div className="answer-number">{answerIndex + 1}</div>
                                            <div className="answer-input">
                                                <input
                                                    type="text"
                                                    value={answer.text}
                                                    onChange={(e) => updateAnswer(question.id, answer.id, 'text', e.target.value)}
                                                    placeholder={`Answer option ${answerIndex + 1}...`}
                                                />
                                            </div>
                                            <button
                                                type="button"
                                                className="delete-answer-btn"
                                                onClick={() => deleteAnswer(question.id, answer.id)}
                                                disabled={question.answers.length <= 2}
                                            >
                                                <DeleteIcon />
                                            </button>
                                        </div>
                                    ))}
                                </div>
                                <button
                                    type="button"
                                    className="add-answer-btn"
                                    onClick={() => addAnswer(question.id)}
                                >
                                    <AddIcon /> Add Answer Option
                                </button>
                            </div>
                        </div>
                    </div>
                ))}
            </div>

            <div className="add-question-section">
                <button
                    type="button"
                    className="add-question-btn"
                    onClick={addQuestion}
                >
                    <AddIcon /> Add New Question
                </button>
            </div>

            {/* Notice Modal */}
            <NoticeModal
                isOpen={modalConfig.isOpen}
                type={modalConfig.type}
                title={modalConfig.title}
                message={modalConfig.message}
                onConfirm={modalConfig.onConfirm}
                onClose={modalConfig.onClose}
                onDecline={modalConfig.onClose}
                confirmText={modalConfig.confirmText}
                declineText={modalConfig.declineText}
                position={modalConfig.position}
                autoClose={modalConfig.type === 'toast'}
                autoCloseTime={3000}
            />
        </div>
    );
};

export default QuestionEditor;