import React, { useState, useEffect } from 'react';
import { getNonce, isPro } from '../Helpers';
import LockIcon from '@mui/icons-material/Lock';
import LoginIcon from '@mui/icons-material/Login';
import PersonAddIcon from '@mui/icons-material/PersonAdd';
import CommentIcon from '@mui/icons-material/Comment';
import ShoppingCartIcon from '@mui/icons-material/ShoppingCart';
import SaveIcon from '@mui/icons-material/Save';
import SecurityIcon from '@mui/icons-material/Security';
import SettingsIcon from '@mui/icons-material/Settings';
import NoticeModal from './NoticeModal/NoticeModal';
import '../styles/_auth-settings.scss';

interface AuthSettingsProps {
    // Props if needed
}

interface FormOption {
    id: number;
    form_name: string;
}

const AuthSettings: React.FC<AuthSettingsProps> = () => {
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);
    const [forms, setForms] = useState<FormOption[]>([]);
    const [isWooCommerceActive, setIsWooCommerceActive] = useState(false);
    const [activeTab, setActiveTab] = useState('forms');
    const [isProUser, setIsProUser] = useState(false); // Check if user has pro version
    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 [settings, setSettings] = useState({
        wp_login_form_id: '',
        wp_registration_form_id: '',
        wc_login_form_id: '',
        wc_registration_form_id: '',
        comment_form_id: '',

        // Login settings
        enable_remember_me: true,
        redirect_after_login: '',
        save_login_to_leads: false,

        // Registration settings
        auto_login_after_registration: true,
        send_welcome_email: true,
        require_email_verification: false,
        password_min_length: 8,
        require_terms_acceptance: false,
        redirect_after_registration: '',
        save_registration_to_leads: false,

        // Security settings
        max_login_attempts: 5,
        lockout_duration: 15,
        enable_captcha_after_failures: false,
    });

    useEffect(() => {
        loadSettings();
        loadForms();
        checkWooCommerce();
        checkProStatus();
    }, []);

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

    const showProModal = () => {
        setModalConfig({
            isOpen: true,
            type: 'premium',
            title: '🚀 Upgrade to Pro',
            message: 'Login & Registration features are available in the Pro version. Upgrade now to unlock advanced authentication, user management, and security features!',
            position: 'center',
            mode: 'success',
            onConfirm: () => {
                window.open('https://wpazleen.com/simple-form-pricing/', '_blank');
                closeModal();
            },
            onClose: closeModal,
            confirmText: 'Upgrade Now',
            declineText: 'Maybe Later'
        });
    };

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

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

    const loadSettings = () => {
        (wp as any).ajax.send('simpleform_get_auth_settings', {
            data: {
                nonce: getNonce(),
            },
            success(response: any) {
                if (response.settings) {
                    setSettings(prev => ({ ...prev, ...response.settings }));
                }
                setLoading(false);
            },
            error(error: any) {
                showToast('error', 'Error', 'Failed to load settings. Please refresh the page.');
                setLoading(false);
            },
        });
    };

    const loadForms = () => {
        (wp as any).ajax.send('simpleform_get_tables', {
            data: {
                nonce: getNonce(),
            },
            success(response: any) {
                setForms(response.tables || []);
            },
            error(error: any) {
                showToast('error', 'Error', 'Failed to load forms list.');
            },
        });
    };

    const checkWooCommerce = () => {
        (wp as any).ajax.send('simpleform_check_woocommerce', {
            data: {
                nonce: getNonce(),
            },
            success(response: any) {
                setIsWooCommerceActive(response.active || false);
            },
            error() {
                setIsWooCommerceActive(false);
            },
        });
    };

    const handleSave = () => {
        setSaving(true);

        (wp as any).ajax.send('simpleform_save_auth_settings', {
            data: {
                nonce: getNonce(),
                settings: settings,
            },
            success(response: any) {
                setSaving(false);
                showToast('success', 'Success', 'Settings saved successfully!');
            },
            error(error: any) {
                setSaving(false);
                showToast('error', 'Error', 'Failed to save settings. Please try again.');
            },
        });
    };

    const handleChange = (field: string, value: any) => {
        setSettings(prev => ({
            ...prev,
            [field]: value
        }));
    };

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

    return (
        <div className="auth-settings-container">
            <div className="auth-settings-header">
                <h1>Login & Registration Settings</h1>
                <p>Configure authentication forms and security settings</p>
            </div>

            {/* Tab Navigation */}
            <div className="auth-settings-tabs">
                <button
                    className={`tab-button ${activeTab === 'forms' ? 'active' : ''}`}
                    onClick={() => setActiveTab('forms')}
                >
                    <SettingsIcon />
                    Form Selection
                </button>
                <button
                    className={`tab-button ${activeTab === 'login' ? 'active' : ''}`}
                    onClick={() => setActiveTab('login')}
                >
                    <LoginIcon />
                    Login Settings
                </button>
                <button
                    className={`tab-button ${activeTab === 'registration' ? 'active' : ''}`}
                    onClick={() => setActiveTab('registration')}
                >
                    <PersonAddIcon />
                    Registration Settings
                </button>
                <button
                    className={`tab-button ${activeTab === 'security' ? 'active' : ''}`}
                    onClick={() => setActiveTab('security')}
                >
                    <SecurityIcon />
                    Security Settings
                </button>
            </div>

            <div className="auth-settings-content">
                {/* Form Selection Tab */}
                {activeTab === 'forms' && (
                    <div className={`settings-section ${!isProUser ? 'pro-locked' : ''}`}>
                        {!isProUser && (
                            <div className="pro-overlay" onClick={showProModal}>
                                <div className="pro-badge">
                                    <LockIcon />
                                    <span>PRO</span>
                                </div>
                            </div>
                        )}
                        <h2>
                            <SettingsIcon /> Form Selection
                        </h2>

                        <div className="settings-grid">
                            {/* WordPress Login */}
                            <div className="setting-item">
                                <label htmlFor="wp_login_form_id">
                                    <LoginIcon className="setting-icon" />
                                    WordPress Login Form
                                </label>
                                <select
                                    id="wp_login_form_id"
                                    value={settings.wp_login_form_id}
                                    onChange={(e) => handleChange('wp_login_form_id', e.target.value)}
                                >
                                    <option value="">Select a form</option>
                                    {forms.map(form => (
                                        <option key={form.id} value={form.id}>
                                            {form.form_name}
                                        </option>
                                    ))}
                                </select>
                                <small>Replace default WordPress login form</small>
                            </div>

                            {/* WordPress Registration */}
                            <div className="setting-item">
                                <label htmlFor="wp_registration_form_id">
                                    <PersonAddIcon className="setting-icon" />
                                    WordPress Registration Form
                                </label>
                                <select
                                    id="wp_registration_form_id"
                                    value={settings.wp_registration_form_id}
                                    onChange={(e) => handleChange('wp_registration_form_id', e.target.value)}
                                >
                                    <option value="">Select a form</option>
                                    {forms.map(form => (
                                        <option key={form.id} value={form.id}>
                                            {form.form_name}
                                        </option>
                                    ))}
                                </select>
                                <small>Replace default WordPress registration form</small>
                            </div>

                            {/* WooCommerce Login */}
                            <div className={`setting-item ${!isWooCommerceActive ? 'disabled' : ''}`}>
                                <label htmlFor="wc_login_form_id">
                                    <ShoppingCartIcon className="setting-icon" />
                                    WooCommerce Login Form
                                    {!isWooCommerceActive && <LockIcon className="lock-icon" />}
                                </label>
                                <select
                                    id="wc_login_form_id"
                                    value={settings.wc_login_form_id}
                                    onChange={(e) => handleChange('wc_login_form_id', e.target.value)}
                                    disabled={!isWooCommerceActive}
                                >
                                    <option value="">Select a form</option>
                                    {forms.map(form => (
                                        <option key={form.id} value={form.id}>
                                            {form.form_name}
                                        </option>
                                    ))}
                                </select>
                                <small>
                                    {isWooCommerceActive
                                        ? 'Replace WooCommerce login form'
                                        : 'Requires WooCommerce plugin'}
                                </small>
                            </div>

                            {/* WooCommerce Registration */}
                            <div className={`setting-item ${!isWooCommerceActive ? 'disabled' : ''}`}>
                                <label htmlFor="wc_registration_form_id">
                                    <ShoppingCartIcon className="setting-icon" />
                                    WooCommerce Registration Form
                                    {!isWooCommerceActive && <LockIcon className="lock-icon" />}
                                </label>
                                <select
                                    id="wc_registration_form_id"
                                    value={settings.wc_registration_form_id}
                                    onChange={(e) => handleChange('wc_registration_form_id', e.target.value)}
                                    disabled={!isWooCommerceActive}
                                >
                                    <option value="">Select a form</option>
                                    {forms.map(form => (
                                        <option key={form.id} value={form.id}>
                                            {form.form_name}
                                        </option>
                                    ))}
                                </select>
                                <small>
                                    {isWooCommerceActive
                                        ? 'Replace WooCommerce registration form'
                                        : 'Requires WooCommerce plugin'}
                                </small>
                            </div>

                            {/* Comment Form */}
                            <div className="setting-item">
                                <label htmlFor="comment_form_id">
                                    <CommentIcon className="setting-icon" />
                                    Comment Form
                                </label>
                                <select
                                    id="comment_form_id"
                                    value={settings.comment_form_id}
                                    onChange={(e) => handleChange('comment_form_id', e.target.value)}
                                >
                                    <option value="">Select a form</option>
                                    {forms.map(form => (
                                        <option key={form.id} value={form.id}>
                                            {form.form_name}
                                        </option>
                                    ))}
                                </select>
                                <small>Replace default comment form</small>
                            </div>
                        </div>
                    </div>
                )}

                {/* Login Settings Tab */}
                {activeTab === 'login' && (
                    <div className={`settings-section ${!isProUser ? 'pro-locked' : ''}`}>
                        {!isProUser && (
                            <div className="pro-overlay" onClick={showProModal}>
                                <div className="pro-badge">
                                    <LockIcon />
                                    <span>PRO</span>
                                </div>
                            </div>
                        )}
                        <h2>
                            <LoginIcon /> Login Settings
                        </h2>

                        <div className="settings-list">
                            <div className="setting-item toggle">
                                <div className="toggle-content">
                                    <div className="toggle-info">
                                        <span className="toggle-label">Enable "Remember Me"</span>
                                        <small>Allow users to stay logged in</small>
                                    </div>
                                    <label className="toggle-switch">
                                        <input
                                            type="checkbox"
                                            checked={settings.enable_remember_me}
                                            onChange={(e) => handleChange('enable_remember_me', e.target.checked)}
                                        />
                                        <span className="toggle-slider"></span>
                                    </label>
                                </div>
                            </div>

                            <div className="setting-item">
                                <label htmlFor="redirect_after_login">
                                    Redirect URL after login
                                </label>
                                <input
                                    type="text"
                                    id="redirect_after_login"
                                    value={settings.redirect_after_login}
                                    onChange={(e) => handleChange('redirect_after_login', e.target.value)}
                                    placeholder="Leave empty for dashboard"
                                />
                                <small>Custom URL to redirect users after successful login</small>
                            </div>

                            <div className="setting-item toggle">
                                <div className="toggle-content">
                                    <div className="toggle-info">
                                        <span className="toggle-label">Save login data to leads</span>
                                        <small>Store login attempts in leads database (username, time, IP)</small>
                                    </div>
                                    <label className="toggle-switch">
                                        <input
                                            type="checkbox"
                                            checked={settings.save_login_to_leads}
                                            onChange={(e) => handleChange('save_login_to_leads', e.target.checked)}
                                        />
                                        <span className="toggle-slider"></span>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                )}

                {/* Registration Settings Tab */}
                {activeTab === 'registration' && (
                    <div className={`settings-section ${!isProUser ? 'pro-locked' : ''}`}>
                        {!isProUser && (
                            <div className="pro-overlay" onClick={showProModal}>
                                <div className="pro-badge">
                                    <LockIcon />
                                    <span>PRO</span>
                                </div>
                            </div>
                        )}
                        <h2>
                            <PersonAddIcon /> Registration Settings
                        </h2>

                        <div className="settings-list">
                            <div className="setting-item toggle">
                                <div className="toggle-content">
                                    <div className="toggle-info">
                                        <span className="toggle-label">Auto-login after registration</span>
                                        <small>Automatically log in users after successful registration</small>
                                    </div>
                                    <label className="toggle-switch">
                                        <input
                                            type="checkbox"
                                            checked={settings.auto_login_after_registration}
                                            onChange={(e) => handleChange('auto_login_after_registration', e.target.checked)}
                                        />
                                        <span className="toggle-slider"></span>
                                    </label>
                                </div>
                            </div>

                            <div className="setting-item toggle">
                                <div className="toggle-content">
                                    <div className="toggle-info">
                                        <span className="toggle-label">Send welcome email</span>
                                        <small>Send WordPress welcome email to new users</small>
                                    </div>
                                    <label className="toggle-switch">
                                        <input
                                            type="checkbox"
                                            checked={settings.send_welcome_email}
                                            onChange={(e) => handleChange('send_welcome_email', e.target.checked)}
                                        />
                                        <span className="toggle-slider"></span>
                                    </label>
                                </div>
                            </div>

                            <div className="setting-item toggle">
                                <div className="toggle-content">
                                    <div className="toggle-info">
                                        <span className="toggle-label">Require email verification</span>
                                        <small>Users must verify email before logging in</small>
                                    </div>
                                    <label className="toggle-switch">
                                        <input
                                            type="checkbox"
                                            checked={settings.require_email_verification}
                                            onChange={(e) => handleChange('require_email_verification', e.target.checked)}
                                        />
                                        <span className="toggle-slider"></span>
                                    </label>
                                </div>
                            </div>

                            <div className="setting-item toggle">
                                <div className="toggle-content">
                                    <div className="toggle-info">
                                        <span className="toggle-label">Require terms acceptance</span>
                                        <small>Users must accept terms and conditions</small>
                                    </div>
                                    <label className="toggle-switch">
                                        <input
                                            type="checkbox"
                                            checked={settings.require_terms_acceptance}
                                            onChange={(e) => handleChange('require_terms_acceptance', e.target.checked)}
                                        />
                                        <span className="toggle-slider"></span>
                                    </label>
                                </div>
                            </div>

                            <div className="setting-item">
                                <label htmlFor="password_min_length">
                                    Password minimum length
                                </label>
                                <input
                                    type="number"
                                    id="password_min_length"
                                    value={settings.password_min_length}
                                    onChange={(e) => handleChange('password_min_length', parseInt(e.target.value))}
                                    min="6"
                                    max="20"
                                />
                                <small>Minimum number of characters required for passwords</small>
                            </div>

                            <div className="setting-item">
                                <label htmlFor="redirect_after_registration">
                                    Redirect URL after registration
                                </label>
                                <input
                                    type="text"
                                    id="redirect_after_registration"
                                    value={settings.redirect_after_registration}
                                    onChange={(e) => handleChange('redirect_after_registration', e.target.value)}
                                    placeholder="Leave empty for dashboard"
                                />
                                <small>Custom URL to redirect users after successful registration</small>
                            </div>

                            <div className="setting-item toggle">
                                <div className="toggle-content">
                                    <div className="toggle-info">
                                        <span className="toggle-label">Save registration data to leads</span>
                                        <small>Store registration data in leads database (all fields except passwords)</small>
                                    </div>
                                    <label className="toggle-switch">
                                        <input
                                            type="checkbox"
                                            checked={settings.save_registration_to_leads}
                                            onChange={(e) => handleChange('save_registration_to_leads', e.target.checked)}
                                        />
                                        <span className="toggle-slider"></span>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                )}

                {/* Security Settings Tab */}
                {activeTab === 'security' && (
                    <div className={`settings-section ${!isProUser ? 'pro-locked' : ''}`}>
                        {!isProUser && (
                            <div className="pro-overlay" onClick={showProModal}>
                                <div className="pro-badge">
                                    <LockIcon />
                                    <span>PRO</span>
                                </div>
                            </div>
                        )}
                        <h2>
                            <SecurityIcon /> Security Settings
                        </h2>

                        <div className="settings-list">
                            <div className="setting-item">
                                <label htmlFor="max_login_attempts">
                                    Maximum login attempts
                                </label>
                                <input
                                    type="number"
                                    id="max_login_attempts"
                                    value={settings.max_login_attempts}
                                    onChange={(e) => handleChange('max_login_attempts', parseInt(e.target.value))}
                                    min="3"
                                    max="10"
                                />
                                <small>Number of failed login attempts before lockout</small>
                            </div>

                            <div className="setting-item">
                                <label htmlFor="lockout_duration">
                                    Lockout duration (minutes)
                                </label>
                                <input
                                    type="number"
                                    id="lockout_duration"
                                    value={settings.lockout_duration}
                                    onChange={(e) => handleChange('lockout_duration', parseInt(e.target.value))}
                                    min="5"
                                    max="60"
                                />
                                <small>How long to lock out users after max attempts</small>
                            </div>

                            <div className="setting-item toggle">
                                <div className="toggle-content">
                                    <div className="toggle-info">
                                        <span className="toggle-label">Enable CAPTCHA after failed attempts</span>
                                        <small>Show CAPTCHA after multiple failed login attempts</small>
                                    </div>
                                    <label className="toggle-switch">
                                        <input
                                            type="checkbox"
                                            checked={settings.enable_captcha_after_failures}
                                            onChange={(e) => handleChange('enable_captcha_after_failures', e.target.checked)}
                                        />
                                        <span className="toggle-slider"></span>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                )}

                {/* Save Button - Always visible */}
                <div className={`settings-actions ${!isProUser ? 'pro-locked' : ''}`}>
                    {!isProUser && (
                        <div className="pro-overlay" onClick={showProModal}>
                            {/* <div className="pro-badge">
                                <LockIcon />
                                <span>PRO</span>
                            </div> */}
                        </div>
                    )}
                    <button
                        className="save-settings-btn"
                        onClick={handleSave}
                        disabled={saving || !isProUser}
                    >
                        <SaveIcon />
                        {saving ? 'Saving...' : 'Save Settings'}
                    </button>
                </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 AuthSettings;
