import React, { useState, useRef, useEffect } from 'react';
import { Link, useLocation } from 'react-router-dom';

const Layout = ({ children }) => {
    const [userMenuOpen, setUserMenuOpen] = useState(false);
    const [frontendSettings, setFrontendSettings] = useState(null);
    const userMenuRef = useRef(null);
    const location = useLocation();

    // Get user data from shopExplorerData
    const userData = window.shopExplorerData?.currentUser || {};
    const isFrontend = !window.location.pathname.includes('wp-admin');

    // Load frontend settings
    useEffect(() => {
        if (isFrontend) {
            // Fetch frontend settings to determine what to show
            fetch(window.shopExplorerData?.apiUrl + '/frontend-settings', {
                headers: {
                    'X-WP-Nonce': window.shopExplorerData?.nonce
                }
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    setFrontendSettings(data.settings);
                }
            })
            .catch(err => console.error('Failed to load frontend settings:', err));
        }
    }, [isFrontend]);

    // Close user menu when clicking outside
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (userMenuRef.current && !userMenuRef.current.contains(event.target)) {
                setUserMenuOpen(false);
            }
        };

        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);

    // Build menu items based on context and settings
    const getMenuItems = () => {
        const baseItems = [
            { path: '/', label: 'Dashboard', icon: '📊', alwaysShow: true },
        ];

        // In admin, show all items
        if (!isFrontend) {
            return [
                ...baseItems,
                { path: '/orders', label: 'Orders', icon: '📦' },
                { path: '/products', label: 'Products', icon: '🛍️' },
                { path: '/customers', label: 'Customers', icon: '👥' },
                { path: '/settings', label: 'Settings', icon: '⚙️' },
            ];
        }

        // In frontend, check settings
        const items = [...baseItems];

        if (frontendSettings?.orders_management?.enabled) {
            items.push({ path: '/orders', label: 'Orders', icon: '📦' });
        }

        if (frontendSettings?.products_management?.enabled) {
            items.push({ path: '/products', label: 'Products', icon: '🛍️' });
        }

        if (frontendSettings?.customer_management?.enabled) {
            items.push({ path: '/customers', label: 'Customers', icon: '👥' });
        }

        // Settings always available in admin context
        if (!isFrontend) {
            items.push({ path: '/settings', label: 'Settings', icon: '⚙️' });
        }

        return items;
    };

    const menuItems = getMenuItems();

    const isActive = (path) => {
        if (path === '/') {
            return location.pathname === '/' || location.pathname === '';
        }
        return location.pathname.startsWith(path);
    };

    const handleLogout = () => {
        if (isFrontend) {
            window.location.href = window.shopExplorerData?.logoutUrl || '/wp-login.php?action=logout';
        } else {
            window.location.href = '/wp-login.php?action=logout';
        }
    };

    const goToWPDashboard = () => {
        window.location.href = '/wp-admin/admin.php?page=shop-explorer#/';
    };

    const goToFrontendDashboard = () => {
        window.location.href = '/shop-explorer-dashboard/';
    };

    return (
        <div className="shop-explorer-layout">
            {/* Header */}
            <header className="layout-header">
                <div className="header-left">
                    <div className="brand">
                        <span className="brand-icon">🛒</span>
                        <span className="brand-name">Shop Explorer</span>
                    </div>
                    <nav className="main-nav">
                        {menuItems.map((item) => (
                            <Link
                                key={item.path}
                                to={item.path}
                                className={`nav-item ${isActive(item.path) ? 'active' : ''}`}
                            >
                                <span className="nav-icon">{item.icon}</span>
                                <span className="nav-label">{item.label}</span>
                            </Link>
                        ))}
                    </nav>
                </div>

                <div className="header-right">
                    <div className="user-menu" ref={userMenuRef}>
                        <button
                            className="user-menu-trigger"
                            onClick={() => setUserMenuOpen(!userMenuOpen)}
                        >
                            <div className="user-avatar">
                                {userData.name ? userData.name.charAt(0).toUpperCase() : 'U'}
                            </div>
                            <div className="user-info">
                                <span className="user-name">{userData.name || 'User'}</span>
                                <span className="user-role">{userData.roles?.[0] || 'user'}</span>
                            </div>
                            <span className="dropdown-arrow">▼</span>
                        </button>

                        {userMenuOpen && (
                            <div className="user-dropdown">
                                <div className="dropdown-header">
                                    <div className="user-avatar-large">
                                        {userData.name ? userData.name.charAt(0).toUpperCase() : 'U'}
                                    </div>
                                    <div className="user-details">
                                        <div className="user-name-large">{userData.name || 'User'}</div>
                                        <div className="user-email">{userData.email || ''}</div>
                                    </div>
                                </div>
                                <div className="dropdown-divider"></div>
                                <div className="dropdown-menu">
                                    {isFrontend && (
                                        <button className="dropdown-item" onClick={goToWPDashboard}>
                                            <span className="item-icon">🏠</span>
                                            <span>WP Dashboard</span>
                                        </button>
                                    )}
                                    {!isFrontend && (
                                        <button className="dropdown-item" onClick={goToFrontendDashboard}>
                                            <span className="item-icon">📊</span>
                                            <span>Frontend Dashboard</span>
                                        </button>
                                    )}
                                    <Link to="/settings" className="dropdown-item" onClick={() => setUserMenuOpen(false)}>
                                        <span className="item-icon">⚙️</span>
                                        <span>Settings</span>
                                    </Link>
                                    <div className="dropdown-divider"></div>
                                    <button className="dropdown-item logout" onClick={handleLogout}>
                                        <span className="item-icon">🚪</span>
                                        <span>Logout</span>
                                    </button>
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            </header>

            {/* Main Content */}
            <main className="layout-content">
                {children}
            </main>
        </div>
    );
};

export default Layout;
