import { useState, useEffect } from '@wordpress/element'
import { Card, CardHeader, CardBody, Button, Spinner } from '@wordpress/components';
import { __, _x, sprintf } from '@wordpress/i18n';
import SettingToggle from './common/SettingToggle';
import { formatDate } from '../helpers/formatting';

const WelcomeDashboard = ({ settings }) => {

    const [isXmlrpcEnabled, setIsXmlrpcEnabled] = useState(settings.wpironis_options?.wpironis_disable_xmlrpc === 1);
    const [isDirectAccessPrevented, setIsDirectAccessPrevented] = useState(settings.wpironis_options?.wpironis_prevent_direct_access === 1);
    const [isSecurityHeadersEnabled, setIsSecurityHeadersEnabled] = useState(settings.wpironis_options?.wpironis_security_headers === 1);
    const [isLimitLoginEnabled, setIsLimitLoginEnabled] = useState(
        settings.login_logout?.enable_limit_login_attempts === '1'
    );
    const [isUserEnumEnabled, setIsUserEnumEnabled] = useState(
        settings.login_logout?.enable_user_enumeration === '1'
    );

    const [isRestApiDisabled, setIsRestApiDisabled] = useState(settings.wpironis_options?.wpironis_disable_rest_api === 1);
    const [isWpVersionHidden, setIsWpVersionHidden] = useState(settings.wpironis_options?.wpironis_hide_wp_version === 1);
    const [isPhpUploadBlocked, setIsPhpUploadBlocked] = useState(settings.wpironis_options?.wpironis_block_php_uploads === 1);
    const [isFrameOptionsEnabled, setIsFrameOptionsEnabled] = useState(settings.wpironis_options?.wpironis_security_header_frame_options === 1);


    const [recentLogs, setRecentLogs] = useState([]);
    const [isLoadingLogs, setIsLoadingLogs] = useState(true);
    const [isSaving, setIsSaving] = useState(false);
    const [notification, setNotification] = useState(null);


    const [systemInfo, setSystemInfo] = useState(null);
    const [isLoadingSystemInfo, setIsLoadingSystemInfo] = useState(true);

    const pluginUrl = (typeof ironSecuritySettings !== 'undefined' && ironSecuritySettings.pluginUrl)
        ? ironSecuritySettings.pluginUrl
        : './wp-content/plugins/iron-security/';

    const logoUrl = `${pluginUrl}admin/img/iron-security.svg`;


    useEffect(() => {

        if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
            const globalSettings = window.ironSecurityDashboard.settings;
            setIsXmlrpcEnabled(globalSettings.wpironis_options?.wpironis_disable_xmlrpc === 1);
            setIsDirectAccessPrevented(globalSettings.wpironis_options?.wpironis_prevent_direct_access === 1);
            setIsSecurityHeadersEnabled(globalSettings.wpironis_options?.wpironis_security_headers === 1);
            setIsLimitLoginEnabled(globalSettings.login_logout?.enable_limit_login_attempts === '1');
            setIsUserEnumEnabled(globalSettings.login_logout?.enable_user_enumeration === '1');
            setIsRestApiDisabled(globalSettings.wpironis_options?.wpironis_disable_rest_api === 1);
            setIsWpVersionHidden(globalSettings.wpironis_options?.wpironis_hide_wp_version === 1);
            setIsPhpUploadBlocked(globalSettings.wpironis_options?.wpironis_block_php_uploads === 1);
            setIsFrameOptionsEnabled(globalSettings.wpironis_options?.wpironis_security_header_frame_options === 1);
        } else {
            setIsXmlrpcEnabled(settings.wpironis_options?.wpironis_disable_xmlrpc === 1);
            setIsDirectAccessPrevented(settings.wpironis_options?.wpironis_prevent_direct_access === 1);
            setIsSecurityHeadersEnabled(settings.wpironis_options?.wpironis_security_headers === 1);
            setIsLimitLoginEnabled(settings.login_logout?.enable_limit_login_attempts === '1');
            setIsUserEnumEnabled(settings.login_logout?.enable_user_enumeration === '1');
            setIsRestApiDisabled(settings.wpironis_options?.wpironis_disable_rest_api === 1);
            setIsWpVersionHidden(settings.wpironis_options?.wpironis_hide_wp_version === 1);
            setIsPhpUploadBlocked(settings.wpironis_options?.wpironis_block_php_uploads === 1);
            setIsFrameOptionsEnabled(settings.wpironis_options?.wpironis_security_header_frame_options === 1);
        }

        fetchRecentLogs();
        fetchSystemInfo();
    }, []);

    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 fetchSystemInfo = () => {
        setIsLoadingSystemInfo(true);

        const data = new FormData();
        data.append('action', 'iron_security_get_system_info');
        data.append('nonce', settings.nonce);

        fetch(settings.ajaxurl, {
            method: 'POST',
            body: data,
            credentials: 'same-origin'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                setSystemInfo(data.data);
            } else {
                console.error('Error fetching system information:', data.data);
                setSystemInfo(null);
            }
            setIsLoadingSystemInfo(false);
        })
        .catch(error => {
            console.error('Error fetching system information:', error);
            setIsLoadingSystemInfo(false);
            setSystemInfo(null);
        });
    };

    const fetchRecentLogs = () => {
        setIsLoadingLogs(true);

        const data = new FormData();
        data.append('action', 'iron_security_get_logs');
        data.append('nonce', settings.nonce);
        data.append('page', 1);
        data.append('per_page', 5);

        fetch(settings.ajaxurl, {
            method: 'POST',
            body: data,
            credentials: 'same-origin'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                setRecentLogs(data.data.logs || []);
            } else {
                console.error('Error fetching recent logs:', data.data);
                setRecentLogs([]);
            }
            setIsLoadingLogs(false);
        })
        .catch(error => {
            console.error('Error fetching recent logs:', error);
            setIsLoadingLogs(false);
            setRecentLogs([]);
        });
    };


    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 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);


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


                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }

                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 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 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 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);


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


                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }

                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);
        }
    };

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

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


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


                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }

                showNotification(__('X-Frame-Options setting updated successfully', 'iron-security'));
            } else {
                throw new Error(data.data || __('Failed to update setting', 'iron-security'));
            }
        } catch (error) {
            console.error('Error updating X-Frame-Options setting:', error);
            setIsFrameOptionsEnabled(!enabled);
            showNotification(error.message || __('Failed to update X-Frame-Options setting', 'iron-security'), 'error');
        } finally {
            setIsSaving(false);
        }
    };

    const getLogTypeLabel = (type) => {
        const logTypes = {
            'login': __('Successful Login', 'iron-security'),
            'failed_login': __('Failed Login', 'iron-security'),
            'lockout': __('Lockout', 'iron-security'),
            'two_factor_auth': __('Two-Factor Auth', 'iron-security'),
            'settings_change': __('Settings Change', 'iron-security'),
            'file_change': __('File Change', 'iron-security'),
            'user_enumeration': __('User Enumeration', 'iron-security'),
            'rest_api': __('REST API Access', 'iron-security'),
            'xml_rpc': __('XML-RPC Access', 'iron-security'),
            'security': __('Security Event', 'iron-security'),
            'admin_action': __('Admin Action', 'iron-security'),
            'user_created': __('User Creation', 'iron-security'),
            'user_modified': __('User Modification', 'iron-security'),
            'plugin_action': __('Plugin Action', 'iron-security'),
            'malicious_request': __('Malicious Request', 'iron-security'),
            'role_change': __('Role Change', 'iron-security'),
            'clickjack_attempt': __('Clickjack Attempt', 'iron-security'),
            'api_request': __('API Request', 'iron-security'),
            'suspicious_behavior': __('Suspicious Activity', 'iron-security'),
            'http_error': __('HTTP Error', 'iron-security'),
            'core_update': __('Core Update', 'iron-security'),
            'theme_action': __('Theme Action', 'iron-security')
        };

        return logTypes[type] || type;
    };

    const getStatusBadge = (status) => {
        const statusClasses = {
            'success': 'success',
            'failure': 'error',
            'warning': 'warning',
            'info': 'info'
        };

        const className = `log-status-badge ${statusClasses[status] || 'default'}`;
        return <span className={className}>{status}</span>;
    };

    return (
        <div className="iron-security-welcome-dashboard">
            {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>
            )}

            {/* System Information section */}
            <Card className="system-info-card">
                <CardHeader>
                    <h3>{__('System Information', 'iron-security')}</h3>
                </CardHeader>
                <CardBody>
                    {isLoadingSystemInfo ? (
                        <div className="system-info-loading">
                            <Spinner />
                            <p>{__('Loading system information...', 'iron-security')}</p>
                        </div>
                    ) : !systemInfo ? (
                        <div className="system-info-error">
                            <p>{__('Unable to load system information. Please refresh the page to try again.', 'iron-security')}</p>
                        </div>
                    ) : (
                        <div className="system-info-grid">
                            {/* WordPress Version */}
                            <div className={`system-info-item ${systemInfo.wp_outdated ? 'warning' : 'good'}`}>
                                <div className="info-header">
                                    <span className="info-icon">
                                        <span className={`dashicons dashicons-${systemInfo.wp_outdated ? 'warning' : 'yes-alt'}`}></span>
                                    </span>
                                    <h4>{__('WordPress Version', 'iron-security')}</h4>
                                </div>
                                <div className="info-content">
                                    <p className="info-value">{systemInfo.wp_version}</p>
                                    {systemInfo.wp_outdated && systemInfo.latest_wp_version && (
                                        <p className="info-message warning">
                                            {sprintf(__('Your WordPress version is outdated. Latest version: %s', 'iron-security'), systemInfo.latest_wp_version)}
                                        </p>
                                    )}
                                    {!systemInfo.wp_outdated && (
                                        <p className="info-message good">
                                            {__('You are running the latest version of WordPress.', 'iron-security')}
                                        </p>
                                    )}
                                </div>
                            </div>

                            {/* PHP Version */}
                            <div className={`system-info-item ${systemInfo.php_outdated ? 'warning' : 'good'}`}>
                                <div className="info-header">
                                    <span className="info-icon">
                                        <span className={`dashicons dashicons-${systemInfo.php_outdated ? 'warning' : 'yes-alt'}`}></span>
                                    </span>
                                    <h4>{__('PHP Version', 'iron-security')}</h4>
                                </div>
                                <div className="info-content">
                                    <p className="info-value">{systemInfo.php_version}</p>
                                    {systemInfo.php_outdated && (
                                        <p className="info-message warning">
                                            {__('PHP version is below 8.0. Security and support for versions below 8.0 will end on January 1, 2026. Consider upgrading for better security and performance.', 'iron-security')}
                                        </p>
                                    )}
                                    {!systemInfo.php_outdated && (
                                        <p className="info-message good">
                                            {__('You are running PHP 8.0 or higher, which is recommended for security and performance.', 'iron-security')}
                                        </p>
                                    )}
                                </div>
                            </div>

                            {/* Server Information */}
                            <div className="system-info-item">
                                <div className="info-header">
                                    <span className="info-icon">
                                        <span className="dashicons dashicons-desktop"></span>
                                    </span>
                                    <h4>{__('Server Information', 'iron-security')}</h4>
                                </div>
                                <div className="info-content">
                                    <p className="info-value">{systemInfo.server_info}</p>
                                </div>
                            </div>

                            {/* Database Version */}
                            <div className="system-info-item">
                                <div className="info-header">
                                    <span className="info-icon">
                                        <span className="dashicons dashicons-database"></span>
                                    </span>
                                    <h4>{__('Database Version', 'iron-security')}</h4>
                                </div>
                                <div className="info-content">
                                    <p className="info-value">{systemInfo.db_version}</p>
                                </div>
                            </div>

                            {/* Admin Users Count */}
                            <div className={`system-info-item ${systemInfo.admin_count > 2 ? 'warning' : 'good'}`}>
                                <div className="info-header">
                                    <span className="info-icon">
                                        <span className={`dashicons dashicons-${systemInfo.admin_count > 2 ? 'warning' : 'admin-users'}`}></span>
                                    </span>
                                    <h4>{__('Admin Users', 'iron-security')}</h4>
                                </div>
                                <div className="info-content">
                                    <p className="info-value">{systemInfo.admin_count}</p>
                                    {systemInfo.admin_count > 2 && (
                                        <p className="info-message warning">
                                            {__('You have multiple administrator accounts. For better security, consider limiting the number of administrator accounts.', 'iron-security')}
                                        </p>
                                    )}
                                    {systemInfo.admin_count <= 2 && (
                                        <p className="info-message good">
                                            {__('You have a reasonable number of administrator accounts.', 'iron-security')}
                                        </p>
                                    )}
                                </div>
                            </div>
                        </div>
                    )}
                </CardBody>
            </Card>

            {/* Essential Security Measures section */}
            <Card className="security-recommendations-card">
                <CardHeader>
                    <h3>{__('Essential Security Measures', 'iron-security')}</h3>
                    <p>{__('These are the most important security features we recommend enabling for your website\'s protection.', 'iron-security')}</p>
                </CardHeader>
                <CardBody>
                    <div className="security-recommendations">
                        <SettingToggle
                            label={__('Disable XML-RPC API', 'iron-security')}
                            description={__('XML-RPC can be a security risk and is often targeted by attackers. We recommend disabling it unless you specifically need it for services like Jetpack.', '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={__('Block PHP Files Execution in Uploads Directory', '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.', 'iron-security')}
                            checked={isPhpUploadBlocked}
                            onChange={handlePhpUploadToggle}
                            disabled={isSaving}
                        />

                        <SettingToggle
                            label={__('Prevent Direct File Access', 'iron-security')}
                            description={__('Block direct access to sensitive WordPress files like wp-config.php and prevent directory listing, significantly improving your site\'s security posture.', 'iron-security')}
                            checked={isDirectAccessPrevented}
                            onChange={handleDirectAccessToggle}
                            disabled={isSaving}
                        />

                        <SettingToggle
                            label={__('Enable X-Frame-Options', 'iron-security')}
                            description={__('Prevents clickjacking attacks by allowing you to specify which sites can display your site in a frame.', 'iron-security')}
                            checked={isFrameOptionsEnabled}
                            onChange={handleFrameOptionsToggle}
                            disabled={isSaving}
                        />

                    </div>
                </CardBody>
            </Card>

            {/* Recent Security Logs */}
            <Card className="recent-logs-card">
                <CardHeader>
                    <h3>{__('Recent Security Logs', 'iron-security')}</h3>
                    <div className="card-action">
                        <Button
                            className="button-primary"
                            onClick={() => {
                                if (typeof window.ironSecurityDashboard !== 'undefined' &&
                                    typeof window.ironSecurityDashboard.setActiveTab === 'function') {
                                    window.ironSecurityDashboard.setActiveTab('logs');
                                } else {
                                    const newUrl = new URL(window.location);
                                    newUrl.searchParams.set('tab', 'logs');
                                    window.history.pushState({}, '', newUrl);
                                    const logsTabButton = document.querySelector('.tab-button.tab-logs');
                                    if (logsTabButton) {
                                        logsTabButton.click();
                                    }
                                }
                            }}
                        >
                            {__('View All Logs', 'iron-security')}
                        </Button>
                    </div>
                </CardHeader>
                <CardBody>
                    {isLoadingLogs ? (
                        <div className="logs-loading">
                            <span className="spinner is-active"></span>
                            <p>{__('Loading recent logs...', 'iron-security')}</p>
                        </div>
                    ) : recentLogs.length === 0 ? (
                        <div className="no-logs">
                            <p>{__('No security logs found. This could be good news - no security events have been recorded yet!', 'iron-security')}</p>
                        </div>
                    ) : (
                        <div className="recent-logs-table-container">
                            <table className="recent-logs-table">
                                <thead>
                                    <tr>
                                        <th>{__('Date', 'iron-security')}</th>
                                        <th>{__('Event', 'iron-security')}</th>
                                        <th>{__('Username', 'iron-security')}</th>
                                        <th>{__('IP Address', 'iron-security')}</th>
                                        <th>{__('Status', 'iron-security')}</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {recentLogs.map(log => (
                                        <tr key={log.id} className={`log-row log-status-${log.status}`}>
                                            <td>{formatDate(log.date_created)}</td>
                                            <td>{getLogTypeLabel(log.log_type)}</td>
                                            <td>{log.username || '-'}</td>
                                            <td>{log.ip_address}</td>
                                            <td>{getStatusBadge(log.status)}</td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    )}
                </CardBody>
            </Card>
        </div>
    );
};

export default WelcomeDashboard;