import {useState, useEffect} from '@wordpress/element';
import WelcomeDashboard from './WelcomeDashboard';
import GeneralSettings from './GeneralSettings';
import LoginLogoutSettings from './LoginLogoutSettings';
import FileDirectoryProtectionSettings from './FileDirectoryProtectionSettings';
import SecurityLogs from './SecurityLogs';
import HttpSecurityHeadersSettings from "./HttpSecurityHeadersSettings";
import Support from './Support';
import { __, sprintf } from '@wordpress/i18n';

const Dashboard = ({settings: initialSettings}) => {
    const [settings, setSettings] = useState(null);
    const [isLoading, setIsLoading] = useState(true);
    const [isTransitioning, setIsTransitioning] = useState(false);

    const getInitialTab = () => {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get('tab') || 'dashboard';
    };

    const [activeTab, setActiveTab] = useState(getInitialTab());

    const fetchFreshSettings = async () => {
        setIsLoading(true);
        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_get_settings');
            formData.append('nonce', initialSettings.nonce);
            const response = await fetch(initialSettings.ajaxurl, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });

            const data = await response.json();
            if (data.success) {
                const {ajaxurl, nonce} = initialSettings;
                setSettings({
                    ...data.data,
                    ajaxurl,
                    nonce
                });
            } else {
                console.error('Failed to fetch fresh settings:', data.data);
            }
        } catch (error) {
            console.error('Error fetching fresh settings:', error);
        } finally {
            setIsLoading(false);
        }
    };

    const handleTabChange = async (tabName) => {
        const newUrl = new URL(window.location);
        newUrl.searchParams.set('tab', tabName);
        window.history.pushState({}, '', newUrl);
        setActiveTab(tabName);
    };

    useEffect(() => {
        const handlePopState = () => {
            const newTab = getInitialTab();
            setActiveTab(newTab);
        };

        window.addEventListener('popstate', handlePopState);
        fetchFreshSettings();


        window.ironSecurityDashboard = {
            setActiveTab: setActiveTab,
            notifySettingsChange: notifySettingsChange
        };

        return () => {
            window.removeEventListener('popstate', handlePopState);

            delete window.ironSecurityDashboard;
        };
    }, []);


    useEffect(() => {
        if (settings && window.ironSecurityDashboard) {
            window.ironSecurityDashboard.settings = settings;
        }
    }, [settings]);


    useEffect(() => {
        const handleStorageChange = (e) => {
            if (e.key === 'iron_security_settings_updated') {

                fetchFreshSettings();
            }
        };

        window.addEventListener('storage', handleStorageChange);

        return () => {
            window.removeEventListener('storage', handleStorageChange);
        };
    }, []);


    const notifySettingsChange = () => {

        localStorage.setItem('iron_security_settings_updated', Date.now().toString());

        setTimeout(() => {
            localStorage.removeItem('iron_security_settings_updated');
        }, 100);
    };

    const tabs = [
        {name: 'dashboard', title: 'Dashboard', className: 'tab-dashboard', icon: 'dashicons-dashboard'},
        {name: 'general', title: 'General Settings', className: 'tab-general', icon: 'dashicons-admin-generic'},
        {
            name: 'login-logout',
            title: __('Authentication', 'iron-security'),
            className: 'tab-login-logout',
            icon: 'dashicons-privacy'
        },
        {
            name: 'file-directory',
            title: __('File & Directory Protection', 'iron-security'),
            className: 'tab-file-directory',
            icon: 'dashicons-portfolio'
        },
        {
            name: 'http-security-headers',
            title: __('HTTP Security & Headers', 'iron-security'),
            className: 'tab-http-security-headers',
            icon: 'dashicons-shield-alt'
        },
        {name: 'logs', title: __('Security Logs', 'iron-security'), className: 'tab-logs', icon: 'dashicons-list-view'},
        {name: 'support', title: __('Support', 'iron-security'), className: 'tab-support', icon: 'dashicons-sos'},
    ];

    const renderContent = () => {
        switch (activeTab) {
            case 'dashboard':
                return <WelcomeDashboard settings={settings}/>;
            case 'general':
                return <GeneralSettings settings={settings}/>;
            case 'login-logout':
                return <LoginLogoutSettings settings={settings}/>;
            case 'file-directory':
                return <FileDirectoryProtectionSettings settings={settings}/>;
            case 'http-security-headers':
                return <HttpSecurityHeadersSettings settings={settings}/>;
            case 'logs':
                return <SecurityLogs settings={settings}/>;
            case 'support':
                return <Support settings={settings}/>;
            default:
                return <WelcomeDashboard settings={settings}/>;
        }
    };

    const Banner = ({type, title, content, ctaText, ctaUrl, image}) => (
        <div className={`iron-security-banner ${type}`}>
            {image && <img src={image} alt={title}/>}
            <div className="iron-security-banner-header">{title}</div>
            <div className="iron-security-banner-content" dangerouslySetInnerHTML={{__html: content}}/>
            {ctaText && ctaUrl && (
                <a href={ctaUrl} className="iron-security-banner-cta" target="_blank" rel="noopener noreferrer">
                    {ctaText}
                </a>
            )}
        </div>
    );


    if (isLoading || !settings) {
        return (
            <div className="iron-security-loading-container">
                <div className="iron-security-loading-content">
                    <div className="iron-security-loading-spinner">
                        <div className="spinner-circle"></div>
                        <div className="spinner-circle"></div>
                        <div className="spinner-circle"></div>
                    </div>
                    <h2>{__('Loading Iron Security', 'iron-security')}</h2>
                    <p>{__('Please wait while we load your security settings...', 'iron-security')}</p>
                    <div className="iron-security-loading-steps">
                        <div className="loading-step">
                            <span className="dashicons dashicons-shield"></span>
                            <span>{__('Initializing security features', 'iron-security')}</span>
                        </div>
                        <div className="loading-step">
                            <span className="dashicons dashicons-lock"></span>
                            <span>{__('Loading security settings', 'iron-security')}</span>
                        </div>
                        <div className="loading-step">
                            <span className="dashicons dashicons-yes-alt"></span>
                            <span>{__('Preparing dashboard', 'iron-security')}</span>
                        </div>
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div className="iron-security-dashboard-wrapper">
            <div className="iron-security-main-container">
                <div className="iron-security-sidebar">
                    {tabs.map((tab) => (
                        <button
                            key={tab.name}
                            className={`tab-button ${activeTab === tab.name ? 'active' : ''}`}
                            onClick={() => handleTabChange(tab.name)}
                        >
                            <span className={`dashicons ${tab.icon}`}></span>
                            {tab.title}
                        </button>
                    ))}
                </div>
                <div className={`iron-security-content ${isTransitioning ? 'transitioning' : ''}`}>
                    <div className="iron-security-content-header">
                        <h2>{tabs.find(tab => tab.name === activeTab)?.title}</h2>
                    </div>
                    {renderContent()}
                </div>
            </div>
            <div className="iron-security-banners">
                <Banner
                    type="Standard"
                    title={__('Love Iron Security?', 'iron-security')}
                    content={sprintf(
                        __('If you like Iron Security, please <a href="%1$s" target="_blank" rel="noopener noreferrer">leave a review</a> or <a href="%2$s" target="_blank" rel="noopener noreferrer">share it</a> with your friends to help us spread the word. We also want to hear your <a href="%3$s" target="_blank" rel="noopener noreferrer">feedback</a> to improve the plugin.', 'iron-security'),
                        'https://wordpress.org/support/plugin/iron-security/reviews/',
                        'https://twitter.com/intent/tweet?text=I%20recommend%20the%20Iron%20Security%20plugin%20for%20WordPress!&url=https://wordpress.org/plugins/iron-security/',
                        'https://wordpress.org/support/plugin/iron-security/'
                    )}
                />
                <Banner
                    type="Standard"
                    title={__('Check Out Our Other Plugins', 'iron-security')}
                    content={sprintf(
                        __('Like this plugin? Check out our other WordPress plugins:<br/><br/><strong><a href="%1$s" target="_blank">Markup for WooCommerce</a></strong><br/><strong><a href="%2$s" target="_blank">Cost of Goods WooCommerce</a></strong><br/><strong><a href="%3$s" target="_blank">Quantity Breaks</a></strong>', 'iron-security'),
                        'https://wordpress.org/plugins/wc-markup/',
                        'https://wordpress.org/plugins/cost-of-goods/',
                        'https://wordpress.org/plugins/quantity-discounts/'
                    )}
                />
            </div>
        </div>
    );
};

export default Dashboard;
