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

const HttpSecurityHeadersSettings = ({settings}) => {

    const [headerSettings, setHeaderSettings] = useState({
        contentTypeOptions: settings.wpironis_options?.wpironis_security_header_content_type_options === 1,
        frameOptions: settings.wpironis_options?.wpironis_security_header_frame_options === 1,
        xssProtection: settings.wpironis_options?.wpironis_security_header_xss_protection === 1,
        strictTransportSecurity: settings.wpironis_options?.wpironis_security_header_strict_transport_security === 1,
        referrerPolicy: settings.wpironis_options?.wpironis_security_header_referrer_policy === 1,
        contentSecurityPolicy: settings.wpironis_options?.wpironis_security_header_content_security_policy === 1,
        permissionsPolicy: settings.wpironis_options?.wpironis_security_header_permissions_policy === 1
    });

    const [isSaving, setIsSaving] = useState(false);
    const [notification, setNotification] = useState(null);

    useEffect(() => {

        if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
            const globalSettings = window.ironSecurityDashboard.settings;
            setHeaderSettings({
                contentTypeOptions: globalSettings.wpironis_options?.wpironis_security_header_content_type_options === 1,
                frameOptions: globalSettings.wpironis_options?.wpironis_security_header_frame_options === 1,
                xssProtection: globalSettings.wpironis_options?.wpironis_security_header_xss_protection === 1,
                strictTransportSecurity: globalSettings.wpironis_options?.wpironis_security_header_strict_transport_security === 1,
                referrerPolicy: globalSettings.wpironis_options?.wpironis_security_header_referrer_policy === 1,
                contentSecurityPolicy: globalSettings.wpironis_options?.wpironis_security_header_content_security_policy === 1,
                permissionsPolicy: globalSettings.wpironis_options?.wpironis_security_header_permissions_policy === 1
            });
        } else {
            setHeaderSettings({
                contentTypeOptions: settings.wpironis_options?.wpironis_security_header_content_type_options === 1,
                frameOptions: settings.wpironis_options?.wpironis_security_header_frame_options === 1,
                xssProtection: settings.wpironis_options?.wpironis_security_header_xss_protection === 1,
                strictTransportSecurity: settings.wpironis_options?.wpironis_security_header_strict_transport_security === 1,
                referrerPolicy: settings.wpironis_options?.wpironis_security_header_referrer_policy === 1,
                contentSecurityPolicy: settings.wpironis_options?.wpironis_security_header_content_security_policy === 1,
                permissionsPolicy: settings.wpironis_options?.wpironis_security_header_permissions_policy === 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 handleHeaderToggle = async (headerName, enabled) => {
        setIsSaving(true);

        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_toggle_security_headers');
            formData.append('header_name', headerName);
            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) {

                const optionNiceNameMap = {
                    'contentTypeOptions': 'X-Content-Type-Options',
                    'frameOptions': 'X-Frame-Options',
                    'xssProtection': 'X-XSS-Protection',
                    'strictTransportSecurity': 'Strict-Transport-Security (HSTS)',
                    'referrerPolicy': 'Referrer-Policy',
                    'contentSecurityPolicy': 'Content-Security-Policy (CSP)',
                    'permissionsPolicy': 'Permissions-Policy'
                };

                setHeaderSettings(prev => ({...prev, [headerName]: enabled}));
                

                if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {

                    const optionNameMap = {
                        'contentTypeOptions': 'wpironis_security_header_content_type_options',
                        'frameOptions': 'wpironis_security_header_frame_options',
                        'xssProtection': 'wpironis_security_header_xss_protection',
                        'strictTransportSecurity': 'wpironis_security_header_strict_transport_security',
                        'referrerPolicy': 'wpironis_security_header_referrer_policy',
                        'contentSecurityPolicy': 'wpironis_security_header_content_security_policy',
                        'permissionsPolicy': 'wpironis_security_header_permissions_policy'
                    };
                    
                    const optionName = optionNameMap[headerName];
                    if (optionName) {
                        window.ironSecurityDashboard.settings.wpironis_options = {
                            ...window.ironSecurityDashboard.settings.wpironis_options,
                            [optionName]: enabled ? 1 : 0
                        };
                        
                        if (window.ironSecurityDashboard.notifySettingsChange) {
                            window.ironSecurityDashboard.notifySettingsChange();
                        }
                    }
                }
                
                showNotification(sprintf(__('%s header setting updated successfully', 'iron-security'), optionNiceNameMap[headerName]));
            } else {
                throw new Error(data.data || __('Failed to update setting', 'iron-security'));
            }
        } catch (error) {
            console.error(`Error updating ${headerName} header setting:`, error);
            setHeaderSettings(prev => ({...prev, [headerName]: !enabled}));
            showNotification(error.message || sprintf(__('Failed to update %s header setting', 'iron-security'), headerName), 'error');
        } finally {
            setIsSaving(false);
        }
    };

    const renderWarningBox = (headerName, title, description, issues = [], recommendations = []) => {
        if (!headerSettings[headerName]) return null;
        
        return (
            <div className="iron-security-warning-box" style={{ marginTop: '8px', marginBottom: '16px', padding: '12px 16px', backgroundColor: '#fcf9e8', border: '1px solid #f0e29a', borderRadius: '4px' }}>
                <h4 style={{ margin: '0 0 8px 0', fontWeight: 'bold', display: 'flex', alignItems: 'center' }}>
                    <span className="dashicons dashicons-warning" style={{ marginRight: '8px', color: '#dba617' }}></span>
                    {title}
                </h4>
                <p style={{ margin: '0 0 8px 0' }}>{description}</p>
                {issues.length > 0 && (
                    <div>
                        <strong>{__("Potential issues:", "iron-security")}</strong>
                        <ul style={{ marginTop: '5px', paddingLeft: '20px' }}>
                            {issues.map((issue, index) => (
                                <li key={index}>{issue}</li>
                            ))}
                        </ul>
                    </div>
                )}
                {recommendations.length > 0 && (
                    <div style={{ marginTop: '8px' }}>
                        <strong>{__("Recommendations:", "iron-security")}</strong>
                        <ul style={{ marginTop: '5px', paddingLeft: '20px' }}>
                            {recommendations.map((rec, index) => (
                                <li key={index}>{rec}</li>
                            ))}
                        </ul>
                    </div>
                )}
            </div>
        );
    };

    return (
        <div className="iron-security-security-features">
            {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", "iron-security")}
                    >
                        <span className="dashicons dashicons-no"/>
                    </button>
                </div>
            )}
            <>
                <CardBody>
                    <div className="iron-security-header-setting">
                        <SettingToggle
                            label={__("X-Content-Type-Options", "iron-security")}
                            description={__("Prevents MIME type sniffing, which helps prevent specific types of attacks where browsers interpret files differently than the server.", "iron-security")}
                            checked={headerSettings.contentTypeOptions}
                            onChange={(enabled) => handleHeaderToggle('contentTypeOptions', enabled)}
                            disabled={isSaving}
                        />
                    </div>
                    
                    {/* X-Frame-Options */}
                    <div className="iron-security-header-setting">
                        <SettingToggle
                            label={__("X-Frame-Options", "iron-security")}
                            description={__("Prevents your site from being embedded in iframes on other websites, protecting against clickjacking attacks.", "iron-security")}
                            checked={headerSettings.frameOptions}
                            onChange={(enabled) => handleHeaderToggle('frameOptions', enabled)}
                            disabled={isSaving}
                        />
                    </div>
                    
                    {/* X-XSS-Protection */}
                    <div className="iron-security-header-setting">
                        <SettingToggle
                            label={__("X-XSS-Protection", "iron-security")}
                            description={__("Enables the browser's built-in XSS (Cross-Site Scripting) filter to block reflected XSS attacks.", "iron-security")}
                            checked={headerSettings.xssProtection}
                            onChange={(enabled) => handleHeaderToggle('xssProtection', enabled)}
                            disabled={isSaving}
                        />
                        {renderWarningBox(
                            'xssProtection',
                            __('About X-XSS-Protection', 'iron-security'),
                            __('This header is considered legacy, but still provides protection in older browsers.', 'iron-security'),
                            [],
                            [__('Generally safe to enable, but modern sites should rely primarily on Content-Security-Policy for XSS protection.', 'iron-security')]
                        )}
                    </div>
                    
                    {/* Strict-Transport-Security */}
                    <div className="iron-security-header-setting">
                        <SettingToggle
                            label={__("Strict-Transport-Security (HSTS)", "iron-security")}
                            description={__("Forces browsers to use HTTPS for your site, even if a user enters or follows an HTTP URL.", "iron-security")}
                            checked={headerSettings.strictTransportSecurity}
                            onChange={(enabled) => handleHeaderToggle('strictTransportSecurity', enabled)}
                            disabled={isSaving}
                        />
                    </div>
                    
                    {/* Referrer-Policy */}
                    <div className="iron-security-header-setting">
                        <SettingToggle
                            label={__("Referrer-Policy", "iron-security")}
                            description={__("Controls how much referrer information is included when users navigate from your site to other sites.", "iron-security")}
                            checked={headerSettings.referrerPolicy}
                            onChange={(enabled) => handleHeaderToggle('referrerPolicy', enabled)}
                            disabled={isSaving}
                        />
                    </div>
                    
                    {/* Content-Security-Policy */}
                    <div className="iron-security-header-setting">
                        <SettingToggle
                            label={__("Content-Security-Policy (CSP)", "iron-security")}
                            description={__("Restricts what resources (JavaScript, CSS, images, etc.) can be loaded by the browser, providing strong protection against XSS and other injection attacks.", "iron-security")}
                            checked={headerSettings.contentSecurityPolicy}
                            onChange={(enabled) => handleHeaderToggle('contentSecurityPolicy', enabled)}
                            disabled={isSaving}
                        />
                        {renderWarningBox(
                            'contentSecurityPolicy',
                            __('Important: Content-Security-Policy Impact', 'iron-security'),
                            __('This is the most powerful but also most disruptive security header. It strictly controls what resources your site can load from other domains.', 'iron-security'),
                            [
                                __('default-src \'self\': Blocks all external resources by default unless specifically allowed.', 'iron-security'),
                                __('script-src: Allows scripts from your site, inline scripts (which are often insecure), and specific third-party sources like WordPress.org, Google Tag Manager, and CDN providers.', 'iron-security'),
                                __('style-src: Allows styles from your site, inline styles, and trusted sources like Google Fonts and CDNs.', 'iron-security'),
                                __('img-src: Limits image loading to your domain and trusted sources like Gravatar and WordPress CDN.', 'iron-security'),
                                __('font-src: Enables fonts from your site and trusted sources like Google Fonts and CDNs.', 'iron-security'),
                                __('frame-src: Restricts embedded content (e.g., iframes) to YouTube, Vimeo, and Google.', 'iron-security')
                            ],
                            [
                                __('This policy can break third-party services like Google Tag Manager, Google Fonts, YouTube embeds, and custom analytics unless their domains are explicitly allowed.', 'iron-security'),
                                __('Inline scripts and styles may stop working unless \'unsafe-inline\' is enabled (not recommended for production).', 'iron-security'),
                                __('After enabling this policy, thoroughly test your website for broken design or functionality.', 'iron-security'),
                                __('Use browser developer tools (Console tab) to identify blocked resources and whitelist only the domains you trust.', 'iron-security'),
                                __('Consider using Report-Only mode first to detect issues before enforcing the policy.', 'iron-security')
                            ]
                        )}
                    </div>
                    
                    {/* Permissions-Policy */}
                    <div className="iron-security-header-setting">
                        <SettingToggle
                            label={__("Permissions-Policy", "iron-security")}
                            description={__("Controls which browser features and APIs (like camera, microphone, geolocation) can be used by your site and embedded content.", "iron-security")}
                            checked={headerSettings.permissionsPolicy}
                            onChange={(enabled) => handleHeaderToggle('permissionsPolicy', enabled)}
                            disabled={isSaving}
                        />
                        
                    </div>
                </CardBody>
            </>
        </div>
    );
};

export default HttpSecurityHeadersSettings;