import React, { useState, useEffect } from 'react';
import LockIcon from '@mui/icons-material/Lock';
import NoticeModal from './../NoticeModal/NoticeModal';
import { getNonce, isPro } from '../../Helpers';

interface QuizSettingsData {
    passing_score: number;
    show_results: boolean;
    show_correct_answers: boolean;
    reward_type: 'none' | 'coupon' | 'redirect';
    reward_value: string;
    redirect_url: string;
    randomize_questions: boolean;
    randomize_answers: boolean;
    time_limit: number;
    collect_name: boolean;
    collect_email: boolean;
    display_mode: 'all_at_once' | 'step_by_step';
    questions_per_step: number;
    step_navigation: 'numbers' | 'custom' | 'progress_bar';
    custom_step_labels: string[];
    require_login: boolean;
    allow_retake: boolean;
    quiz_tracking: 'ip_address' | 'browser_storage' | 'hybrid';
}

interface QuizSettingsProps {
    settings: QuizSettingsData;
    onUpdate: (settings: QuizSettingsData) => void;
}

const QuizSettings: React.FC<QuizSettingsProps> = ({ settings, onUpdate }) => {
    const [isProUser, setIsProUser] = useState(false);
    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'
    });

    useEffect(() => {
        const isProuser = isPro();
        setIsProUser(isProuser);
    }, []);

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

    const showProModal = () => {
        // alert('�Enjoy an awesome limited-time discount before it expires!');
        setModalConfig({
            isOpen: true,
            type: 'premium',
            title: '🚀 Upgrade to Pro',
            message: '�Enjoy an awesome limited-time discount before it expires!',
            position: 'center',
            mode: 'success',
            onConfirm: () => {
                window.open('https://wpazleen.com/simple-form-pricing/', '_blank');
                closeModal();
            },
            onClose: closeModal,
            confirmText: 'Upgrade Now',
            declineText: 'Maybe Later'
        });
    };

    const updateSetting = (field: keyof QuizSettingsData, value: any) => {
        onUpdate({
            ...settings,
            [field]: value,
        });
    };

    return (
        <div className="quiz-settings">
            <div className={`settings-section ${!isProUser ? 'pro-locked' : ''}`}>

                {!isProUser && (
                    <div className="pro-overlay" onClick={showProModal}>
                        <div className="pro-badge">
                            <LockIcon />
                            <span>PRO</span>
                        </div>
                    </div>
                )}

                <h3>Scoring & Results</h3>

                <div className="form-group">
                    <label>Passing Score (%)</label>
                    <input
                        type="number"
                        min="0"
                        max="100"
                        value={settings.passing_score}
                        onChange={(e) => updateSetting('passing_score', parseInt(e.target.value) || 0)}
                    />
                    <small>Minimum score required to pass the quiz (0-100)</small>
                </div>

                <div className="form-group checkbox-group">
                    <label>
                        <input
                            type="checkbox"
                            checked={settings.show_results}
                            onChange={(e) => updateSetting('show_results', e.target.checked)}
                        />
                        Show results to user after submission
                    </label>
                </div>

                <div className="form-group checkbox-group">
                    <label>
                        <input
                            type="checkbox"
                            checked={settings.show_correct_answers}
                            onChange={(e) => updateSetting('show_correct_answers', e.target.checked)}
                        />
                        Show correct answers after submission
                    </label>
                </div>
            </div>

            <div className={`settings-section ${!isProUser ? 'pro-locked' : ''}`}>
                {!isProUser && (
                    <div className="pro-overlay" onClick={showProModal}>
                        <div className="pro-badge">
                            <LockIcon />
                            <span>PRO</span>
                        </div>
                    </div>
                )}
                <h3>Rewards</h3>

                <div className="form-group">
                    <label>Reward Type</label>
                    <select
                        value={settings.reward_type}
                        onChange={(e) => updateSetting('reward_type', e.target.value)}
                        disabled={!isProUser}
                    >
                        <option value="none">No Reward</option>
                        <option value="coupon">Coupon Code</option>
                        <option value="redirect">Redirect to URL</option>
                    </select>
                    <small>Reward users who pass the quiz</small>
                </div>

                {settings.reward_type === 'coupon' && (
                    <div className="form-group">
                        <label>Coupon Code</label>
                        <input
                            type="text"
                            value={settings.reward_value}
                            onChange={(e) => updateSetting('reward_value', e.target.value)}
                            placeholder="Enter coupon code"
                            disabled={!isProUser}
                        />
                        <small>This code will be displayed to users who pass</small>
                    </div>
                )}

                {settings.reward_type === 'redirect' && (
                    <div className="form-group">
                        <label>Redirect URL</label>
                        <input
                            type="url"
                            value={settings.redirect_url}
                            onChange={(e) => updateSetting('redirect_url', e.target.value)}
                            placeholder="https://example.com/success"
                            disabled={!isProUser}
                        />
                        <small>Users will be redirected here after passing</small>
                    </div>
                )}
            </div>

            <div className={`settings-section ${!isProUser ? 'pro-locked' : ''}`}>

                {!isProUser && (
                    <div className="pro-overlay" onClick={showProModal}>
                        <div className="pro-badge">
                            <LockIcon />
                            <span>PRO</span>
                        </div>
                    </div>
                )}

                <h3>User Information</h3>

                <div className="form-group checkbox-group">
                    <label>
                        <input
                            type="checkbox"
                            checked={settings.collect_name}
                            onChange={(e) => updateSetting('collect_name', e.target.checked)}
                        />
                        Collect user name
                    </label>
                    <small>Show name field before quiz starts</small>
                </div>

                <div className="form-group checkbox-group">
                    <label>
                        <input
                            type="checkbox"
                            checked={settings.collect_email}
                            onChange={(e) => updateSetting('collect_email', e.target.checked)}
                        />
                        Collect user email
                    </label>
                    <small>Show email field before quiz starts</small>
                </div>
            </div>

            <div className={`settings-section ${!isProUser ? 'pro-locked' : ''}`}>
                {!isProUser && (
                    <div className="pro-overlay" onClick={showProModal}>
                        <div className="pro-badge">
                            <LockIcon />
                            <span>PRO</span>
                        </div>
                    </div>
                )}
                <h3>Quiz Behavior</h3>

                <div className="form-group checkbox-group">
                    <label>
                        <input
                            type="checkbox"
                            checked={settings.randomize_questions}
                            onChange={(e) => updateSetting('randomize_questions', e.target.checked)}
                            disabled={!isProUser}
                        />
                        Randomize question order
                    </label>
                </div>

                <div className="form-group checkbox-group">
                    <label>
                        <input
                            type="checkbox"
                            checked={settings.randomize_answers}
                            onChange={(e) => updateSetting('randomize_answers', e.target.checked)}
                            disabled={!isProUser}
                        />
                        Randomize answer order
                    </label>
                </div>

                <div className="form-group">
                    <label>Time Limit (minutes)</label>
                    <input
                        type="number"
                        min="0"
                        value={settings.time_limit}
                        onChange={(e) => updateSetting('time_limit', parseInt(e.target.value) || 0)}
                        disabled={!isProUser}
                    />
                    <small>Set to 0 for no time limit</small>
                </div>
            </div>

            <div className={`settings-section ${!isProUser ? 'pro-locked' : ''}`}>
                {!isProUser && (
                    <div className="pro-overlay" onClick={showProModal}>
                        <div className="pro-badge">
                            <LockIcon />
                            <span>PRO</span>
                        </div>
                    </div>
                )}
                <h3>Access Control</h3>

                <div className="form-group checkbox-group">
                    <label>
                        <input
                            type="checkbox"
                            checked={settings.require_login}
                            onChange={(e) => updateSetting('require_login', e.target.checked)}
                            disabled={!isProUser}
                        />
                        Require login to take quiz
                    </label>
                    <small>Only logged-in users can take this quiz</small>
                </div>

                <div className="form-group checkbox-group">
                    <label>
                        <input
                            type="checkbox"
                            checked={settings.allow_retake}
                            onChange={(e) => updateSetting('allow_retake', e.target.checked)}
                            disabled={!isProUser}
                        />
                        Allow users to retake quiz
                    </label>
                    <small>Users can take the quiz multiple times</small>
                </div>

                <div className="form-group">
                    <label>Quiz Tracking Method</label>
                    <select
                        value={settings.quiz_tracking}
                        onChange={(e) => updateSetting('quiz_tracking', e.target.value)}
                        disabled={!isProUser}
                    >
                        <option value="hybrid">Hybrid (IP + Browser Storage)</option>
                        <option value="ip_address">IP Address Only</option>
                        <option value="browser_storage">Browser Storage Only</option>
                    </select>
                    <small>How to track if users have already taken the quiz</small>
                </div>
            </div>

            <div className={`settings-section ${!isProUser ? 'pro-locked' : ''}`}>
                {!isProUser && (
                    <div className="pro-overlay" onClick={showProModal}>
                        <div className="pro-badge">
                            <LockIcon />
                            <span>PRO</span>
                        </div>
                    </div>
                )}
                <h3>Display Mode</h3>

                <div className="form-group">
                    <label>Question Display</label>
                    <select
                        value={settings.display_mode}
                        onChange={(e) => updateSetting('display_mode', e.target.value)}
                        disabled={!isProUser}
                    >
                        <option value="all_at_once">Show All Questions at Once</option>
                        <option value="step_by_step">Step by Step</option>
                    </select>
                    <small>Choose how questions are presented to users</small>
                </div>

                {settings.display_mode === 'step_by_step' && (
                    <>
                        <div className="form-group">
                            <label>Questions per Step</label>
                            <input
                                type="number"
                                min="1"
                                max="10"
                                value={settings.questions_per_step}
                                onChange={(e) => updateSetting('questions_per_step', parseInt(e.target.value) || 1)}
                                disabled={!isProUser}
                            />
                            <small>Number of questions to show per step (1-10)</small>
                        </div>

                        <div className="form-group">
                            <label>Step Navigation Style</label>
                            <select
                                value={settings.step_navigation}
                                onChange={(e) => updateSetting('step_navigation', e.target.value)}
                                disabled={!isProUser}
                            >
                                <option value="numbers">Numbers (1, 2, 3...)</option>
                                <option value="progress_bar">Progress Bar</option>
                                <option value="custom">Custom Labels</option>
                            </select>
                            <small>How to display step progress</small>
                        </div>

                        {settings.step_navigation === 'custom' && (
                            <div className="form-group">
                                <label>Custom Step Labels</label>
                                <textarea
                                    value={settings.custom_step_labels.join('\n')}
                                    onChange={(e) => updateSetting('custom_step_labels', e.target.value.split('\n').filter(label => label.trim()))}
                                    placeholder="Enter one label per line&#10;e.g.:&#10;Getting Started&#10;Personal Info&#10;Preferences&#10;Review"
                                    rows={4}
                                    disabled={!isProUser}
                                />
                                <small>One label per line. Leave empty to use default numbering.</small>
                            </div>
                        )}
                    </>
                )}
            </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 QuizSettings;
