import React, { useState } from 'react';
import styles from './Sidebar.module.css';
import logo from '../../assets/logo.png';
import { SIDEBAR_DATA } from './SidebarData';
import { ICONS } from './SidebarIcons';

const Sidebar = ({ isCollapsed, toggleCollapse, currentView, onNavigate, currentUser }) => {
    // State to track expanded menu items (by ID)
    const [expandedItems, setExpandedItems] = useState({});

    const toggleExpand = (id, e) => {
        e.stopPropagation();
        setExpandedItems(prev => ({
            ...prev,
            [id]: !prev[id]
        }));
    };

    // Recursive function to render menu items
    const renderMenuItem = (item, level = 0) => {
        const hasChildren = item.children && item.children.length > 0;
        const isExpanded = expandedItems[item.id];
        // Indentation logic: Level 0 = 0, Level 1 = 1rem, etc.
        const paddingLeft = isCollapsed ? '1rem' : `${1 + (level * 0.8)}rem`;

        // If collapsed, only show top-level items or specific icons
        if (isCollapsed && level > 0) return null;

        // Resolve icon
        const iconElement = ICONS[item.icon] || item.icon || (level > 0 ? '•' : '');

        return (
            <div key={item.id}>
                <div
                    className={`${styles.navItem} ${currentView === item.label ? styles.active : ''}`}
                    onClick={() => {
                        // Always navigate if label is provided
                        if (onNavigate) onNavigate(item.label);

                        // Also toggle expansion if it has children
                        if (hasChildren && !isCollapsed) {
                            toggleExpand(item.id, { stopPropagation: () => { } });
                        }
                    }}
                    style={{ paddingLeft }}
                    title={isCollapsed ? item.label : ''}
                >
                    <span className={styles.icon}>
                        {iconElement}
                    </span>

                    {!isCollapsed && (
                        <>
                            <span className={styles.label}>{item.label}</span>
                            {hasChildren && (
                                <span className={`${styles.arrow} ${isExpanded ? styles.expanded : ''}`}>
                                    ▶
                                </span>
                            )}
                        </>
                    )}
                </div>

                {/* Render Children */}
                {hasChildren && isExpanded && !isCollapsed && (
                    <div className={styles.subMenu}>
                        {item.children.map(child => renderMenuItem(child, level + 1))}
                    </div>
                )}
            </div>
        );
    };

    const dashboardItem = { id: 'dashboard', label: 'Dashboard', icon: 'dashboard' };
    const adminUsersItem = { id: 'users', label: 'Users', icon: 'users' };

    return (
        <aside className={`${styles.sidebar} ${isCollapsed ? styles.collapsed : ''}`}>
            <div className={styles.toggleBtn} onClick={toggleCollapse}>
                {isCollapsed ? '➡' : '⬅'}
            </div>
            <div className={styles.logo} style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', padding: '1rem' }}>
                {!isCollapsed ? (
                    <img src={logo} alt="Weststar Engineering" style={{ maxWidth: '100%', height: 'auto', borderRadius: '4px' }} />
                ) : (
                    <span style={{ fontWeight: 'bold', color: 'var(--accent-primary)' }}>WE</span>
                )}
            </div>

            <nav className={styles.nav}>
                {/* Dashboard (Always First) */}
                {renderMenuItem(dashboardItem)}

                {/* Admin Users Link (If Admin) */}
                {currentUser?.role === 'Admin' && renderMenuItem(adminUsersItem)}

                {/* Generated Menu Items */}
                {SIDEBAR_DATA.map(item => renderMenuItem(item))}
            </nav>

            <div
                className={styles.userProfile}
                onClick={() => onNavigate && onNavigate('Profile')}
            >
                <div style={{
                    width: '40px', height: '40px',
                    borderRadius: '50%',
                    overflow: 'hidden', flexShrink: 0,
                    border: '2px solid var(--accent-primary)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    backgroundColor: 'var(--bg-secondary)', color: 'var(--text-primary)'
                }}>
                    {currentUser?.photo ? (
                        <img src={currentUser.photo} alt="User" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                    ) : (
                        currentUser?.name ? currentUser.name.substring(0, 2).toUpperCase() : 'U'
                    )}
                </div>

                {!isCollapsed && (
                    <div style={{ display: 'flex', flexDirection: 'column', whiteSpace: 'nowrap', overflow: 'hidden' }}>
                        <span style={{ fontSize: '0.9rem', fontWeight: 600, color: 'var(--text-primary)' }}>{currentUser?.name || 'User'}</span>
                        <span style={{ fontSize: '0.75rem', color: 'var(--text-secondary)' }}>{currentUser?.role || 'Staff'}</span>
                    </div>
                )}
            </div>
        </aside>
    );
};

export default Sidebar;
