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

const FileDirectoryProectionSettings = ({settings}) => {

    const [isPhpUploadBlocked, setIsPhpUploadBlocked] = useState(settings.wpironis_options?.wpironis_block_php_uploads === 1);
    const [isDirectAccessPrevented, setIsDirectAccessPrevented] = useState(settings.wpironis_options?.wpironis_prevent_direct_access === 1);

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

    useEffect(() => {

        setIsPhpUploadBlocked(settings.wpironis_options?.wpironis_block_php_uploads === 1);
        setIsDirectAccessPrevented(settings.wpironis_options?.wpironis_prevent_direct_access === 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 handleDirectAccessToggle = async (enabled) => {
        setIsSaving(true);

        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_toggle_direct_access');
            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) {
                setIsDirectAccessPrevented(enabled);
                showNotification(data.data.message || __('Direct file access protection setting updated successfully', 'iron-security'));
            } else {
                throw new Error(data.data || __('Failed to update setting', 'iron-security'));
            }
        } catch (error) {
            console.error('Error updating direct file access protection setting:', error);
            setIsDirectAccessPrevented(!enabled);
            showNotification(error.message || __('Failed to update direct file access protection setting', 'iron-security'), 'error');
        } finally {
            setIsSaving(false);
        }
    };

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

        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_toggle_php_uploads');
            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) {
                setIsPhpUploadBlocked(enabled);
                showNotification(data.data.message || __('PHP file upload blocking setting updated successfully', 'iron-security'));
            } else {
                throw new Error(data.data || __('Failed to update setting', 'iron-security'));
            }
        } catch (error) {
            console.error('Error updating PHP upload blocking setting:', error);
            setIsPhpUploadBlocked(!enabled);
            showNotification(error.message || __('Failed to update PHP upload blocking setting', 'iron-security'), 'error');
        } finally {
            setIsSaving(false);
        }
    };

    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"
                    >
                        <span className="dashicons dashicons-no"/>
                    </button>
                </div>
            )}
            <>
                <CardBody>
                    <SettingToggle
                        label={__("Block PHP File Uploads", 'iron-security')}
                        description={__("Prevents uploading of PHP and other executable files through the media library. This is a critical security feature that stops attackers from uploading malicious files that could be executed on your server. Also adds protection at the .htaccess level.", 'iron-security')}
                        checked={isPhpUploadBlocked}
                        onChange={handlePhpUploadToggle}
                        disabled={isSaving}
                    />
                    <SettingToggle
                        label={__("Prevent Direct File Access", 'iron-security')}
                        description={__("Blocks direct access to sensitive WordPress files like wp-config.php, .htaccess, readme.html, and other system files. Also prevents directory listing and protects includes directories from unauthorized access.", 'iron-security')}
                        checked={isDirectAccessPrevented}
                        onChange={handleDirectAccessToggle}
                        disabled={isSaving}
                    />
                </CardBody>
            </>
        </div>
    );
};

export default FileDirectoryProectionSettings;