import React, { useState, useEffect } from 'react';
import { getNonce, isPro } from '../../Helpers';
import NoticeModal from '../NoticeModal/NoticeModal';
import AddIcon from '@mui/icons-material/Add';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';
import QuizIcon from '@mui/icons-material/Quiz';
import VisibilityIcon from '@mui/icons-material/Visibility';
import AssessmentIcon from '@mui/icons-material/Assessment';
import LockIcon from '@mui/icons-material/Lock';

// Declare wp global for WordPress
declare const wp: any;

interface Quiz {
    id: number;
    quiz_name: string;
    description: string;
    initial_form_id: number | null;
    questions: any[];
    settings: any;
    created_at: string;
    updated_at: string;
}

interface QuizListProps {
    onCreateQuiz: () => void;
    onEditQuiz: (quiz: Quiz) => void;
    onViewResults: (quiz: Quiz) => void;
}

const QuizList: React.FC<QuizListProps> = ({ onCreateQuiz, onEditQuiz, onViewResults }) => {
    const [quizzes, setQuizzes] = useState<Quiz[]>([]);
    const [loading, setLoading] = useState(true);
    const [deleting, setDeleting] = useState<number | null>(null);
    const [isProUser, setIsProUser] = useState(false);
    const [previewUrl, setPreviewUrl] = useState<string | null>(null);

    const [modalConfig, setModalConfig] = useState({
        isOpen: false,
        type: 'confirmation',
        title: '',
        message: '',
        onConfirm: () => { },
        confirmText: 'Confirm',
        declineText: 'Cancel',
        mode: 'success',
        position: 'center' as 'center' | 'top-right'
    });

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

    useEffect(() => {
        loadQuizzes();
        checkProStatus();
    }, []);

    const checkProStatus = () => {
        const isProuser = isPro();
        setIsProUser(isProuser);
    };

    const showProModal = () => {
        setModalConfig({
            isOpen: true,
            type: 'premium',
            title: '🚀 Upgrade to Pro',
            message: 'Create unlimited quizzes with Pro! Free version is limited to 1 quiz. Upgrade now to unlock unlimited quizzes and advanced features!',
            mode: 'success',
            onConfirm: () => {
                window.open('https://wpazleen.com/simple-form-pricing/', '_blank');
                closeModal();
            },
            confirmText: 'Upgrade Now',
            declineText: 'Maybe Later',
            position: 'center'
        });
    };

    const handleCreateQuiz = () => {
        if (!isProUser && quizzes.length >= 1) {
            showProModal();
            return;
        }
        onCreateQuiz();
    };

    const loadQuizzes = () => {
        setLoading(true);
        (wp as any).ajax.send('simpleform_get_quizzes', {
            data: {
                nonce: getNonce(),
            },
            success(response: any) {
                if (response.quizzes) {
                    setQuizzes(response.quizzes);
                }
                setLoading(false);
            },
            error(error: any) {
                console.error('Error loading quizzes:', error);
                setLoading(false);
            },
        });
    };

    const handleDelete = (quiz: Quiz) => {
        setModalConfig({
            isOpen: true,
            type: 'confirmation',
            title: 'Delete Quiz',
            message: `Are you sure you want to delete "${quiz.quiz_name}"? This action cannot be undone.`,
            mode: 'warning',
            onConfirm: () => {
                setDeleting(quiz.id);
                (wp as any).ajax.send('simpleform_delete_quiz', {
                    data: {
                        nonce: getNonce(),
                        quiz_id: quiz.id,
                    },
                    success(response: any) {
                        setQuizzes(prev => prev.filter(q => q.id !== quiz.id));
                        setDeleting(null);

                        setModalConfig({
                            isOpen: true,
                            type: 'toast',
                            title: 'Success',
                            message: `Quiz "${quiz.quiz_name}" deleted successfully`,
                            position: 'top-right',
                            mode: 'success',
                            onConfirm: () => {},
                            confirmText: 'OK',
                            declineText: 'Cancel',
                        });
                        setTimeout(closeModal, 3000);
                    },
                    error(error: any) {
                        console.error('Error deleting quiz:', error);
                        setDeleting(null);

                        setModalConfig({
                            isOpen: true,
                            type: 'toast',
                            title: 'Error',
                            message: 'Failed to delete quiz. Please try again.',
                            position: 'top-right',
                            mode: 'error',
                            onConfirm: () => {},
                            confirmText: 'OK',
                            declineText: 'Cancel',
                        });
                        setTimeout(closeModal, 3000);
                    },
                });
                closeModal();
            },
            confirmText: 'Yes, Delete',
            declineText: 'Cancel',
            position: 'center'
        });
    };

    const handlePreview = (quiz: Quiz) => {
        (wp as any).ajax.send('simpleform_get_quiz_preview_url', {
            data: {
                nonce: getNonce(),
                quiz_id: quiz.id,
            },
            success(response: any) {
                if (response.preview_url) {
                    setPreviewUrl(response.preview_url);
                }
            },
            error(error: any) {
                console.error('Error getting preview URL:', error);
                setModalConfig({
                    isOpen: true,
                    type: 'toast',
                    title: 'Error',
                    message: 'Failed to generate preview URL.',
                    position: 'top-right',
                    mode: 'error',
                    onConfirm: () => {},
                    confirmText: 'OK',
                    declineText: 'Cancel',
                });
                setTimeout(closeModal, 3000);
            },
        });
    };

    const closePreview = () => {
        setPreviewUrl(null);
    };

    const formatDate = (dateString: string) => {
        return new Date(dateString).toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'short',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
    };

    if (loading) {
        return (
            <div className="quiz-loading">
                <div className="spinner"></div>
                <p>Loading quizzes...</p>
            </div>
        );
    }

    return (
        <div className="quiz-list-container">
            <div className="quiz-list-header">
                <div className="header-content">
                    <h1>
                        <QuizIcon />
                        Quizzes
                    </h1>
                    <p>Create interactive quizzes to engage your audience and collect leads</p>
                </div>
                <button
                    className={`create-quiz-btn ${!isProUser && quizzes.length >= 1 ? 'pro-locked-btn' : ''}`}
                    onClick={handleCreateQuiz}
                >
                    <AddIcon />
                    Create Quiz
                    {!isProUser && quizzes.length >= 1 && <LockIcon style={{ marginLeft: '8px', fontSize: '18px' }} />}
                </button>
            </div>

            {quizzes.length === 0 ? (
                <div className="no-quizzes">
                    <div className="no-quizzes-content">
                        <QuizIcon className="no-quizzes-icon" />
                        <h3>No quizzes yet</h3>
                        <p>Create your first quiz to start engaging with your audience</p>
                        <button className="create-first-quiz-btn" onClick={onCreateQuiz}>
                            <AddIcon />
                            Create Your First Quiz
                        </button>
                    </div>
                </div>
            ) : (
                <div className="quiz-grid">
                    {quizzes.map(quiz => (
                        <div key={quiz.id} className="quiz-card">
                            <div className="quiz-card-header">
                                <div className="quiz-icon">
                                    <QuizIcon />
                                </div>
                                <div className="quiz-info">
                                    <h3>{quiz.quiz_name}</h3>
                                    <p className="quiz-description">
                                        {quiz.description || 'No description'}
                                    </p>
                                </div>
                            </div>

                            <div className="quiz-stats">
                                <div className="stat">
                                    <span className="stat-label">Questions:</span>
                                    <span className="stat-value">{quiz.questions?.length || 0}</span>
                                </div>
                                <div className="stat">
                                    <span className="stat-label">Passing Score:</span>
                                    <span className="stat-value">{quiz.settings?.passing_score || 70}%</span>
                                </div>
                                <div className="stat">
                                    <span className="stat-label">Created:</span>
                                    <span className="stat-value">{formatDate(quiz.created_at)}</span>
                                </div>
                            </div>

                            <div className="quiz-actions">
                                <button
                                    className="action-btn edit-btn"
                                    onClick={() => onEditQuiz(quiz)}
                                    title="Edit Quiz"
                                >
                                    <EditIcon />
                                </button>
                                <button
                                    className="action-btn results-btn"
                                    onClick={() => onViewResults(quiz)}
                                    title="View Results"
                                >
                                    <AssessmentIcon />
                                </button>
                                <button
                                    className="action-btn preview-btn"
                                    onClick={() => handlePreview(quiz)}
                                    title="Preview Quiz"
                                >
                                    <VisibilityIcon />
                                </button>
                                <button
                                    className="action-btn delete-btn"
                                    onClick={() => handleDelete(quiz)}
                                    disabled={deleting === quiz.id}
                                    title="Delete Quiz"
                                >
                                    {deleting === quiz.id ? (
                                        <div className="mini-spinner"></div>
                                    ) : (
                                        <DeleteIcon />
                                    )}
                                </button>
                            </div>

                            <div className="quiz-shortcode">
                                <label>Shortcode:</label>
                                <code>[simple_quiz id="{quiz.id}"]</code>
                                <button
                                    className="copy-shortcode-btn"
                                    onClick={() => {
                                        navigator.clipboard.writeText(`[simple_quiz id="${quiz.id}"]`);
                                    }}
                                    title="Copy shortcode"
                                >
                                    Copy
                                </button>
                            </div>
                        </div>
                    ))}
                </div>
            )}

            <NoticeModal
                isOpen={modalConfig.isOpen}
                onClose={closeModal}
                onConfirm={modalConfig.onConfirm}
                onDecline={closeModal}
                type={modalConfig.type}
                mode={modalConfig.mode}
                title={modalConfig.title}
                message={modalConfig.message}
                confirmText={modalConfig.confirmText}
                declineText={modalConfig.declineText}
                position={modalConfig.position || 'center'}
                autoClose={modalConfig.type === 'toast'}
                autoCloseTime={3000}
            />

            {previewUrl && (
                <div className="preview-modal-overlay" onClick={closePreview}>
                    <div className="preview-modal-container" onClick={(e) => e.stopPropagation()}>
                        <div className="preview-modal-header">
                            <h2>Quiz Preview</h2>
                            <button className="preview-modal-close" onClick={closePreview}>×</button>
                        </div>
                        <div className="preview-modal-body">
                            <iframe
                                src={previewUrl}
                                title="Quiz Preview"
                                className="preview-iframe"
                            />
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default QuizList;
