import { useState, useEffect } from '@wordpress/element'
import {Card, CardHeader, CardBody} from '@wordpress/components';
import SettingToggle from './common/SettingToggle';
import { __, sprintf } from '@wordpress/i18n';

const GeneralSettings = ({settings}) => {
    const [isXmlrpcEnabled, setIsXmlrpcEnabled] = useState(settings.wpironis_options?.wpironis_disable_xmlrpc === 1);
    const [isWpVersionHidden, setIsWpVersionHidden] = useState(settings.wpironis_options?.wpironis_hide_wp_version === 1);
    const [isFileEditorDisabled, setIsFileEditorDisabled] = useState(settings.wpironis_options?.wpironis_disable_file_editor === 1);
    const [isRestApiDisabled, setIsRestApiDisabled] = useState(settings.wpironis_options?.wpironis_disable_rest_api === 1);
    const [isPluginAutoUpdateEnabled, setIsPluginAutoUpdateEnabled] = useState(settings.wpironis_options?.wpironis_enable_plugin_autoupdate === 1);
    const [isCoreAutoUpdateEnabled, setIsCoreAutoUpdateEnabled] = useState(settings.wpironis_options?.wpironis_enable_core_autoupdate === 1);
    const [isAIBotsBlocked, setIsAIBotsBlocked] = useState(settings.wpironis_options?.wpironis_block_ai_bots === 1);
    const [isSaving, setIsSaving] = useState(false);
    const [notification, setNotification] = useState(null);

    useEffect(() => {

        if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
            const globalSettings = window.ironSecurityDashboard.settings;
            setIsXmlrpcEnabled(globalSettings.wpironis_options?.wpironis_disable_xmlrpc === 1);
            setIsWpVersionHidden(globalSettings.wpironis_options?.wpironis_hide_wp_version === 1);
            setIsFileEditorDisabled(globalSettings.wpironis_options?.wpironis_disable_file_editor === 1);
            setIsRestApiDisabled(globalSettings.wpironis_options?.wpironis_disable_rest_api === 1);
            setIsPluginAutoUpdateEnabled(globalSettings.wpironis_options?.wpironis_enable_plugin_autoupdate === 1);
            setIsCoreAutoUpdateEnabled(globalSettings.wpironis_options?.wpironis_enable_core_autoupdate === 1);
            setIsAIBotsBlocked(globalSettings.wpironis_options?.wpironis_block_ai_bots === 1);
        } else {
            setIsXmlrpcEnabled(settings.wpironis_options?.wpironis_disable_xmlrpc === 1);
            setIsWpVersionHidden(settings.wpironis_options?.wpironis_hide_wp_version === 1);
            setIsFileEditorDisabled(settings.wpironis_options?.wpironis_disable_file_editor === 1);
            setIsRestApiDisabled(settings.wpironis_options?.wpironis_disable_rest_api === 1);
            setIsPluginAutoUpdateEnabled(settings.wpironis_options?.wpironis_enable_plugin_autoupdate === 1);
            setIsCoreAutoUpdateEnabled(settings.wpironis_options?.wpironis_enable_core_autoupdate === 1);
            setIsAIBotsBlocked(settings.wpironis_options?.wpironis_block_ai_bots === 1);
        }
    }, [settings]);

    useEffect(() => {
        if (notification) {
            document.body.classList.add('iron-security-notification-active');
        } else {
            document.body.classList.remove('iron-security-notification-active');
        }
        return () => {
            document.body.classList.remove('iron-security-notification-active');
        };
    }, [notification]);

    const showNotification = (message, type = 'success') => {
        setNotification({message, type});
        setTimeout(() => setNotification(null), 3000);
    };

    const handleXmlrpcToggle = async (enabled) => {
        setIsSaving(true);

        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_toggle_xmlrpc');
            formData.append('enabled', enabled);
            formData.append('nonce', settings.nonce);

            const response = await fetch(settings.ajaxurl, {
                method: 'POST',
                credentials: 'same-origin',
                body: formData
            });

            const data = await response.json();

            if (data.success) {
                setIsXmlrpcEnabled(enabled);
                

                if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
                    window.ironSecurityDashboard.settings.wpironis_options = {
                        ...window.ironSecurityDashboard.settings.wpironis_options,
                        wpironis_disable_xmlrpc: enabled ? 1 : 0
                    };
                    

                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }
                
                showNotification(data.data.message || __('XML-RPC setting updated successfully', 'iron-security'));
            } else {
                throw new Error(data.data || __('Failed to update setting', 'iron-security'));
            }
        } catch (error) {
            console.error('Error updating XML-RPC setting:', error);
            setIsXmlrpcEnabled(!enabled);
            showNotification(error.message || __('Failed to update XML-RPC setting', 'iron-security'), 'error');
        } finally {
            setIsSaving(false);
        }
    };

    const handleWpVersionToggle = async (enabled) => {
        setIsSaving(true);

        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_toggle_wp_version');
            formData.append('enabled', enabled);
            formData.append('nonce', settings.nonce);

            const response = await fetch(settings.ajaxurl, {
                method: 'POST',
                credentials: 'same-origin',
                body: formData
            });

            const data = await response.json();

            if (data.success) {
                setIsWpVersionHidden(enabled);
                

                if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
                    window.ironSecurityDashboard.settings.wpironis_options = {
                        ...window.ironSecurityDashboard.settings.wpironis_options,
                        wpironis_hide_wp_version: enabled ? 1 : 0
                    };
                    

                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }
                
                showNotification(data.data.message || __('WordPress version visibility setting updated successfully', 'iron-security'));
            } else {
                throw new Error(data.data || __('Failed to update setting', 'iron-security'));
            }
        } catch (error) {
            console.error('Error updating WordPress version setting:', error);
            setIsWpVersionHidden(!enabled);
            showNotification(error.message || __('Failed to update WordPress version setting', 'iron-security'), 'error');
        } finally {
            setIsSaving(false);
        }
    };

    const handleFileEditorToggle = async (enabled) => {
        setIsSaving(true);

        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_toggle_file_editor');
            formData.append('enabled', enabled);
            formData.append('nonce', settings.nonce);

            const response = await fetch(settings.ajaxurl, {
                method: 'POST',
                credentials: 'same-origin',
                body: formData
            });

            const data = await response.json();

            if (data.success) {
                setIsFileEditorDisabled(enabled);
                

                if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
                    window.ironSecurityDashboard.settings.wpironis_options = {
                        ...window.ironSecurityDashboard.settings.wpironis_options,
                        wpironis_disable_file_editor: enabled ? 1 : 0
                    };
                    

                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }
                
                showNotification(data.data.message || __('File editor setting updated successfully', 'iron-security'));

                if (enabled) {
                    setTimeout(() => {
                        showNotification(__('Please refresh the page for the file editor changes to take effect', 'iron-security'), 'info');
                    }, 3500);
                }
            } else {
                throw new Error(data.data || __('Failed to update setting', 'iron-security'));
            }
        } catch (error) {
            console.error('Error updating file editor setting:', error);
            setIsFileEditorDisabled(!enabled);
            showNotification(error.message || __('Failed to update file editor setting', 'iron-security'), 'error');
        } finally {
            setIsSaving(false);
        }
    };

    const handleRestApiToggle = async (enabled) => {
        setIsSaving(true);
        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_toggle_rest_api');
            formData.append('enabled', enabled);
            formData.append('nonce', settings.nonce);

            const response = await fetch(settings.ajaxurl, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });

            const data = await response.json();

            if (data.success) {
                setIsRestApiDisabled(enabled);
                

                if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
                    window.ironSecurityDashboard.settings.wpironis_options = {
                        ...window.ironSecurityDashboard.settings.wpironis_options,
                        wpironis_disable_rest_api: enabled ? 1 : 0
                    };
                    

                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }
                
                showNotification(data.data.message || __('REST API setting updated successfully', 'iron-security'));
            } else {
                throw new Error(data.data || __('Failed to update setting', 'iron-security'));
            }
        } catch (error) {
            console.error('Error:', error);
            showNotification(error.message || __('Failed to update REST API setting', 'iron-security'), 'error');
            setIsRestApiDisabled(!enabled);
        } finally {
            setIsSaving(false);
        }
    };

    const handlePluginAutoUpdateToggle = async (enabled) => {
        setIsSaving(true);
        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_toggle_plugin_autoupdate');
            formData.append('enabled', enabled);
            formData.append('nonce', settings.nonce);

            const response = await fetch(settings.ajaxurl, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });

            const data = await response.json();

            if (data.success) {
                setIsPluginAutoUpdateEnabled(enabled);
                

                if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
                    window.ironSecurityDashboard.settings.wpironis_options = {
                        ...window.ironSecurityDashboard.settings.wpironis_options,
                        wpironis_enable_plugin_autoupdate: enabled ? 1 : 0
                    };
                    

                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }
                
                showNotification(data.data.message || __('Plugin auto-update setting updated successfully', 'iron-security'));
            } else {
                throw new Error(data.data || __('Failed to update setting', 'iron-security'));
            }
        } catch (error) {
            console.error('Error:', error);
            showNotification(error.message || __('Failed to update plugin auto-update setting', 'iron-security'), 'error');
            setIsPluginAutoUpdateEnabled(!enabled);
        } finally {
            setIsSaving(false);
        }
    };

    const handleCoreAutoUpdateToggle = async (enabled) => {
        setIsSaving(true);
        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_toggle_core_autoupdate');
            formData.append('enabled', enabled);
            formData.append('nonce', settings.nonce);

            const response = await fetch(settings.ajaxurl, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });

            const data = await response.json();

            if (data.success) {
                setIsCoreAutoUpdateEnabled(enabled);
                

                if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
                    window.ironSecurityDashboard.settings.wpironis_options = {
                        ...window.ironSecurityDashboard.settings.wpironis_options,
                        wpironis_enable_core_autoupdate: enabled ? 1 : 0
                    };
                    

                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }
                
                showNotification(data.data.message || __('Core auto-update setting updated successfully', 'iron-security'));
            } else {
                throw new Error(data.data || __('Failed to update setting', 'iron-security'));
            }
        } catch (error) {
            console.error('Error:', error);
            showNotification(error.message || __('Failed to update core auto-update setting', 'iron-security'), 'error');
            setIsCoreAutoUpdateEnabled(!enabled);
        } finally {
            setIsSaving(false);
        }
    };

    const handleAIBotBlockingToggle = async (enabled) => {
        setIsSaving(true);
        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_toggle_ai_bot_blocking');
            formData.append('enabled', enabled);
            formData.append('nonce', settings.nonce);

            const response = await fetch(settings.ajaxurl, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });

            const data = await response.json();

            if (data.success) {
                setIsAIBotsBlocked(enabled);
                

                if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
                    window.ironSecurityDashboard.settings.wpironis_options = {
                        ...window.ironSecurityDashboard.settings.wpironis_options,
                        wpironis_block_ai_bots: enabled ? 1 : 0
                    };
                    

                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }
                
                showNotification(data.data.message || __('AI bot blocking setting updated successfully', 'iron-security'));
            } else {
                throw new Error(data.data || __('Failed to update AI bot blocking setting', 'iron-security'));
            }
        } catch (error) {
            console.error('Error:', error);
            showNotification(error.message || __('Failed to update AI bot blocking setting', 'iron-security'), 'error');
            setIsAIBotsBlocked(!enabled);
        } finally {
            setIsSaving(false);
        }
    };

    return (
        <>
            {notification && (
                <div className={`iron-security-notification ${notification.type}`}>
                    <span
                        className={`dashicons dashicons-${notification.type === 'success' ? 'yes' : notification.type === 'info' ? 'info' : 'warning'}`}/>
                    <span className="message">{notification.message}</span>
                    <button
                        className="close-button"
                        onClick={() => setNotification(null)}
                        aria-label="Close notification"
                    >
                        <span className="dashicons dashicons-no"/>
                    </button>
                </div>
            )}
            <div className="iron-security-general-settings">
                <>
                    <CardBody>
                        <SettingToggle
                            label={__("Disable XML-RPC API", 'iron-security')}
                            description={__("XML-RPC is a remote procedure call (RPC) protocol that uses XML to encode its calls and HTTP as a transport mechanism. While it enables features like remote posting and Jetpack connectivity, it can be a security risk. Enabling this setting will disable XML-RPC for better security.", 'iron-security')}
                            checked={isXmlrpcEnabled}
                            onChange={handleXmlrpcToggle}
                            disabled={isSaving}
                        />

                        <SettingToggle
                            label={__("Disable REST API", 'iron-security')}
                            description={__("Disables the WordPress REST API for non-authenticated users. This helps prevent potential security vulnerabilities and unauthorized access to your site's data through the API endpoints.", 'iron-security')}
                            checked={isRestApiDisabled}
                            onChange={handleRestApiToggle}
                            disabled={isSaving}
                        />

                        <SettingToggle
                            label={__("Hide WordPress Version", 'iron-security')}
                            description={__("Removes the WordPress version number from your site's HTML, RSS feeds, and script/style sources. This helps prevent attackers from easily identifying potential vulnerabilities based on your WordPress version.", 'iron-security')}
                            checked={isWpVersionHidden}
                            onChange={handleWpVersionToggle}
                            disabled={isSaving}
                        />

                        <SettingToggle
                            label={__("Disable File Editor", 'iron-security')}
                            description={__("Disables the built-in file editor in WordPress admin. This prevents potential attackers who gain admin access from directly editing theme and plugin files through the WordPress dashboard. Requires a page refresh to take effect.", 'iron-security')}
                            checked={isFileEditorDisabled}
                            onChange={handleFileEditorToggle}
                            disabled={isSaving}
                        />

                        <SettingToggle
                            label={__("Enable Plugin Auto-Updates",'iron-security')}
                            description={__("Automatically update all plugins when new versions are available. This helps keep your site secure by ensuring plugins are always up to date.", 'iron-security')}
                            checked={isPluginAutoUpdateEnabled}
                            onChange={handlePluginAutoUpdateToggle}
                            disabled={isSaving}
                        />

                        <SettingToggle
                            label={__("Enable Core Auto-Updates", 'iron-security')}
                            description={__("Automatically update WordPress core when new versions are available. This ensures your site has the latest security patches and features.", 'iron-security')}
                            checked={isCoreAutoUpdateEnabled}
                            onChange={handleCoreAutoUpdateToggle}
                            disabled={isSaving}
                        />

                        <SettingToggle
                            label={__("Block AI Bots", 'iron-security')}
                            description={__("Block AI bots from crawling and scraping your website", 'iron-security')}
                            checked={isAIBotsBlocked}
                            onChange={handleAIBotBlockingToggle}
                            disabled={isSaving}
                        />
                    </CardBody>
                </>
            </div>
        </>
    );
};

export default GeneralSettings; 