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

interface PollSettingsData {
    allow_multiple: boolean;
    show_results: 'always' | 'after_vote' | 'never';
    allow_revote: boolean;
    require_login: boolean;
    close_date: string;
    result_display: 'percentage' | 'count' | 'both';
    collect_name: boolean;
    collect_email: boolean;
    hide_after_submit: boolean;
    reward_type: 'none' | 'redirect' | 'coupon';
    redirect_url: string;
    coupon_code: string;
    vote_tracking: 'ip_address' | 'browser_storage' | 'hybrid';
    display_mode: 'all_at_once' | 'step_by_step';
    answers_per_step: number;
    step_navigation: 'numbers' | 'custom' | 'progress_bar';
    custom_step_labels: string[];
    poll_type: 'single_question' | 'multiple_questions';
}

interface PollSettingsProps {
    settings: PollSettingsData;
    onUpdate: (settings: PollSettingsData) => void;
}

const PollSettings: React.FC<PollSettingsProps> = ({ 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 PollSettingsData, value: any) => {
        // Show warning when switching poll types
        if (field === 'poll_type' && value !== settings.poll_type) {
            const message = value === 'multiple_questions' 
                ? 'Switching to Multiple Questions Survey will convert your current answers into the first survey question. Continue?'
                : 'Switching to Single Question Poll will use only the first question from your survey. Continue?';
            
            setModalConfig({
                isOpen: true,
                type: 'confirmation',
                title: 'Change Poll Type',
                message: message,
                position: 'center',
                mode: 'success',
                onConfirm: () => {
                    onUpdate({
                        ...settings,
                        [field]: value,
                    });
                    closeModal();
                },
                onClose: closeModal,
                confirmText: 'Continue',
                declineText: 'Cancel'
            });
            return; // Don't change immediately, wait for confirmation
        }
        
        onUpdate({
            ...settings,
            [field]: value,
        });
    };

    return (
        <div className="poll-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>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 poll 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 poll 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>Voting Options</h3>

                <div className="form-group checkbox-group">
                    <label>
                        <input
                            type="checkbox"
                            checked={settings.allow_multiple}
                            onChange={(e) => updateSetting('allow_multiple', e.target.checked)}
                        />
                        Allow multiple answer selection
                    </label>
                    <small>Users can select more than one answer</small>
                </div>

                <div className="form-group checkbox-group">
                    <label>
                        <input
                            type="checkbox"
                            checked={settings.allow_revote}
                            onChange={(e) => updateSetting('allow_revote', e.target.checked)}
                        />
                        Allow users to change their vote
                    </label>
                    <small>Users can vote again to change their answer</small>
                </div>

                <div className="form-group checkbox-group">
                    <label>
                        <input
                            type="checkbox"
                            checked={settings.require_login}
                            onChange={(e) => updateSetting('require_login', e.target.checked)}
                        />
                        Require login to vote
                    </label>
                    <small>Only logged-in users can participate</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>Results Display</h3>

                <div className="form-group">
                    <label>Show Results</label>
                    <select
                        value={settings.show_results}
                        onChange={(e) => updateSetting('show_results', e.target.value)}
                        disabled={!isProUser}
                    >
                        <option value="always">Always show results</option>
                        <option value="after_vote">Show after voting</option>
                        <option value="never">Never show results</option>
                    </select>
                    <small>When to display poll results to users</small>
                </div>

                <div className="form-group">
                    <label>Result Display Format</label>
                    <select
                        value={settings.result_display}
                        onChange={(e) => updateSetting('result_display', e.target.value)}
                        disabled={!isProUser}
                    >
                        <option value="percentage">Percentage only</option>
                        <option value="count">Vote count only</option>
                        <option value="both">Both percentage and count</option>
                    </select>
                    <small>How to display the voting results</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>Poll Schedule</h3>

                <div className="form-group">
                    <label>Close Date (Optional)</label>
                    <input
                        type="datetime-local"
                        value={settings.close_date}
                        onChange={(e) => updateSetting('close_date', e.target.value)}
                        disabled={!isProUser}
                    />
                    <small>Poll will automatically close on this date. Leave empty for no expiration.</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>Poll Behavior</h3>

                <div className="form-group checkbox-group">
                    <label>
                        <input
                            type="checkbox"
                            checked={settings.hide_after_submit}
                            onChange={(e) => updateSetting('hide_after_submit', e.target.checked)}
                            disabled={!isProUser}
                        />
                        Hide poll after submission
                    </label>
                    <small>Hide the poll form after user submits their vote</small>
                </div>

                <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="redirect">Redirect to page</option>
                        <option value="coupon">Show coupon code</option>
                    </select>
                    <small>What to do after user completes the poll</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/thank-you"
                            disabled={!isProUser}
                        />
                        <small>URL to redirect users after voting</small>
                    </div>
                )}

                {settings.reward_type === 'coupon' && (
                    <div className="form-group">
                        <label>Coupon Code</label>
                        <input
                            type="text"
                            value={settings.coupon_code}
                            onChange={(e) => updateSetting('coupon_code', e.target.value)}
                            placeholder="SAVE20"
                            disabled={!isProUser}
                        />
                        <small>Coupon code to display after voting</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>Poll Type</h3>

                <div className="form-group">
                    <label>Question Structure</label>
                    <select
                        value={settings.poll_type}
                        onChange={(e) => updateSetting('poll_type', e.target.value)}
                        disabled={!isProUser}
                    >
                        <option value="single_question">Single Question Poll</option>
                        <option value="multiple_questions">Multiple Questions Survey</option>
                    </select>
                    <small>
                        <strong>Single Question:</strong> One question with multiple answer choices<br/>
                        <strong>Multiple Questions:</strong> Survey-style with multiple questions, each having their own answers
                    </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>Answer Display</label>
                    <select
                        value={settings.display_mode}
                        onChange={(e) => updateSetting('display_mode', e.target.value)}
                        disabled={!isProUser}
                    >
                        <option value="all_at_once">Show All Answers at Once</option>
                        <option value="step_by_step">Step-by-Step Navigation</option>
                    </select>
                    <small>Choose how poll answers are displayed to users</small>
                </div>

                {settings.display_mode === 'step_by_step' && (
                    <>
                        <div className="form-group">
                            <label>Answers Per Step</label>
                            <input
                                type="number"
                                min="1"
                                max="10"
                                value={settings.answers_per_step}
                                onChange={(e) => updateSetting('answers_per_step', parseInt(e.target.value) || 1)}
                                disabled={!isProUser}
                            />
                            <small>Number of answer options to show per step</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 indicators</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;Category A&#10;Category B&#10;Final Choice"
                                    rows={4}
                                    disabled={!isProUser}
                                />
                                <small>Enter custom labels for each step (one per line)</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>Vote Tracking</h3>

                <div className="form-group">
                    <label>Vote Detection Method</label>
                    <select
                        value={settings.vote_tracking}
                        onChange={(e) => updateSetting('vote_tracking', e.target.value)}
                        disabled={!isProUser}
                    >
                        <option value="ip_address">IP Address (Server-side)</option>
                        <option value="browser_storage">Browser Storage (Client-side)</option>
                        <option value="hybrid">Hybrid (IP + Browser Storage)</option>
                    </select>
                    <small>
                        <strong>IP Address:</strong> Tracks votes by user's IP address. Works across browsers but may block multiple users behind same IP.<br/>
                        <strong>Browser Storage:</strong> Uses localStorage. Allows multiple votes from same IP but different browsers/devices.<br/>
                        <strong>Hybrid:</strong> Uses both methods for maximum security and flexibility.
                    </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 PollSettings;
