import React, { useState, useEffect } from 'react';
import CourtOfArms from '../assets/Court of Arms.png';
import { NavLink, useLocation } from 'react-router-dom';
import {
    HomeIcon,
    XIcon,
    ChevronDownIcon,
    ChevronRightIcon,
    ChevronLeftIcon,
    FileTextIcon,
    BarChart3Icon,
    TrendingUpIcon,
    MessageSquareIcon,
    ClipboardListIcon,
    UsersIcon,
    SettingsIcon,
    ShieldIcon,
    AlertTriangleIcon,
    PieChartIcon,
    UserCheckIcon,
    BellIcon,
    DatabaseIcon,
    ActivityIcon,
    LockIcon,
    Menu // Added for hamburger toggle
} from 'lucide-react';

// Mock user context for admin - replace with actual UserContext
const useUser = () => ({
    user: { full_name: 'Admin User', roles: ['admin'] },
    hasPermission: () => true
});

const navSections = [
    {
        name: 'Overview',
        items: [
            { 
                to: '/admin/dashboard', 
                label: 'Dashboard', 
                icon: <HomeIcon className="w-5 h-5" />, 
                permissions: ['dashboard:view'] 
            },
            // { 
            //     to: '/admin/analytics', 
            //     label: 'Analytics', 
            //     icon: <BarChart3Icon className="w-5 h-5" />, 
            //     permissions: ['analytics:view'] 
            // }
        ]
    },
    {
        name: 'Citizen Services',
        items: [
            { 
                to: '/admin/complaints', 
                label: 'Complaints Mgt', 
                icon: <MessageSquareIcon className="w-5 h-5" />, 
                permissions: ['complaints:view']
            },
            {
                to: '/admin/polls-surveys',
                label: 'Polls & Surveys',
                icon: <ClipboardListIcon className="w-5 h-5" />,
                permissions: ['polls:view']
            },
            // { 
            //     to: '/admin/feedback', 
            //     label: 'Chatbot & Feedback', 
            //     icon: <MessageSquareIcon className="w-5 h-5" />, 
            //     permissions: ['feedback:view'] 
            // }
        ]
    },
    {
        name: 'User Management',
        items: [
            {
                to: '/admin/users',
                label: 'User Management',
                icon: <UsersIcon className="w-5 h-5" />,
                permissions: ['users:view'],
                hasDropdown: true,
                subItems: [
                    { to: '/admin/users/all', label: 'Users', icon: <UsersIcon className="w-4 h-4" /> },
                    { to: '/admin/users/roles', label: 'Roles & Permissions', icon: <LockIcon className="w-4 h-4" /> },
                    { to: '/admin/users/activity', label: 'User Activity', icon: <ActivityIcon className="w-4 h-4" /> }
                ]
            }
        ]
    },
    {
        name: 'Tenants',
        items: [
            {
                to: '/admin/tenants',
                label: 'Tenants',
                icon: <DatabaseIcon className="w-5 h-5" />,
                permissions: ['tenants:view']
            }
        ]
    },
    {
        name: 'Reports & Analytics',
        items: [
            {
                to: '/admin/reports',
                label: 'System Reports',
                icon: <BarChart3Icon className="w-5 h-5" />,
                permissions: ['reports:view'],
                hasDropdown: true,
                subItems: [
                    { to: '/admin/reports/engagement', label: 'Citizen Engagement', icon: <TrendingUpIcon className="w-4 h-4" /> },
                    // { to: '/admin/reports/complaints', label: 'Complaints Analytics', icon: <MessageSquareIcon className="w-4 h-4" /> },
                    // { to: '/admin/reports/polls', label: 'Poll Participation', icon: <ClipboardListIcon className="w-4 h-4" /> },
                    { to: '/admin/reports/usage', label: 'System Usage', icon: <ActivityIcon className="w-4 h-4" /> },
                    { to: '/admin/reports/performance', label: 'Performance Metrics', icon: <PieChartIcon className="w-4 h-4" /> }
                ]
            }
        ]
    },
    {
        name: 'System',
        items: [
            { 
                to: '/admin/notifications', 
                label: 'Notifications', 
                icon: <BellIcon className="w-5 h-5" />, 
                permissions: ['notifications:view'] 
            },
            {
                to: '/admin/settings',
                label: 'System Settings',
                icon: <SettingsIcon className="w-5 h-5" />,
                permissions: ['settings:view']
                // hasDropdown: true,
                // subItems: [
                    // { to: '/admin/settings/general', label: 'General Settings', icon: <SettingsIcon className="w-4 h-4" /> },
                    // { to: '/admin/settings/security', label: 'Security', icon: <LockIcon className="w-4 h-4" /> },
                    // { to: '/admin/settings/maintenance', label: 'Maintenance', icon: <AlertTriangleIcon className="w-4 h-4" /> },
                    // { to: '/admin/settings/backup', label: 'Backup & Recovery', icon: <DatabaseIcon className="w-4 h-4" /> }
                // ]
            }
        ]
    }
];

export default function AdminSidebar({ open, minimized, isMobile, onClose, onMinimize, onOpen }) {
    const { user, hasPermission } = useUser();
    const location = useLocation();
    const [openDropdowns, setOpenDropdowns] = useState({});

    // Helper to check if a user has at least one of the required permissions for an item
    const checkItemPermissions = (itemPermissions) => {
        if (!itemPermissions || itemPermissions.length === 0) {
            return true;
        }
        if (user?.roles?.includes('admin')) {
            return true; // Admin has all permissions
        }
        return itemPermissions.some(p => user?.permissions?.includes(p));
    };

    const toggleDropdown = (itemLabel) => {
        setOpenDropdowns(prev => ({
            ...prev,
            [itemLabel]: !prev[itemLabel]
        }));
    };

    if (!user) return null;

    // Sidebar classes for mobile vs desktop
    const getSidebarClasses = () => {
        if (isMobile) {
            // Mobile: overlay when open, hidden when closed
            return `
                flex flex-col h-full shadow-2xl
                bg-blue-900 text-white
                transition-all duration-300 ease-in-out
                fixed inset-y-0 left-0 z-50 w-64
                ${open ? 'translate-x-0' : '-translate-x-full'}
            `;
        } else {
            // Desktop: always visible, can be minimized
            return `
                flex flex-col h-full shadow-2xl
                bg-blue-900 text-white
                transition-all duration-300 ease-in-out
                relative
                ${minimized ? 'w-20' : 'w-64'}
            `;
        }
    };

    // Helper: Close sidebar on mobile when clicking a link
    const handleNavLinkClick = () => {
        if (isMobile && onClose) {
            onClose();
        }
    };

    return (
        <>
            {/* Mobile Hamburger Toggle - Embedded and self-contained */}
            {isMobile && !open && (
                <button
                    onClick={onOpen}
                    className="fixed top-4 left-4 z-50 p-2 rounded-md bg-blue-900 text-white shadow-lg"
                    aria-label="Open sidebar"
                >
                    <Menu className="w-6 h-6" />
                </button>
            )}

            {/* Sidebar Container */}
            <div className={getSidebarClasses()}>
                {/* Sidebar Header */}
                <div className="flex items-center justify-between px-4 py-4 border-b border-blue-800/70">
                    <div className="flex items-center space-x-2 overflow-hidden">
                        {(!isMobile || open) && (!minimized || isMobile) && (
                            <div className="flex items-center space-x-3">
                                <h1 className="text-lg font-bold tracking-tight text-white whitespace-nowrap font-poppins">
                                    Admin Portal
                                </h1>
                            </div>
                        )}
                        {/* {!isMobile && minimized && (
                            // <img src={CourtOfArms} alt="Court of Arms" className="w-8 h-8 object-contain mx-auto" />
                        )} */}
                    </div>
                    <div className="flex items-center space-x-1">
                        {/* Minimize/Expand button (desktop only) */}
                        {!isMobile && (
                            <button
                                onClick={onMinimize}
                                className="p-1 rounded-md text-gray-300 hover:bg-blue-800 hover:text-white focus:outline-none focus:ring-2 focus:ring-inset focus:ring-orange-400"
                                aria-label={minimized ? "Expand sidebar" : "Minimize sidebar"}
                            >
                                {minimized ? <ChevronRightIcon className="w-5 h-5" /> : <ChevronLeftIcon className="w-5 h-5" />}
                            </button>
                        )}
                        {/* Close button (mobile only) */}
                        {isMobile && (
                            <button
                                onClick={onClose}
                                className="p-1 rounded-md text-gray-300 hover:bg-blue-800 hover:text-white focus:outline-none focus:ring-2 focus:ring-inset focus:ring-orange-400"
                                aria-label="Close sidebar"
                            >
                                <XIcon className="w-6 h-6" />
                            </button>
                        )}
                    </div>
                </div>

                {/* Navigation Links */}
                <nav className={`flex-1 ${minimized && open ? 'px-1 py-2' : 'px-2 py-4'} ${minimized && open ? 'space-y-2' : 'space-y-4'} overflow-y-auto custom-scrollbar ${minimized && open ? 'items-center' : ''}`}> 
                    {navSections.map((section, index) => {
                        const filteredItems = section.items.filter(item => checkItemPermissions(item.permissions));

                        if (filteredItems.length === 0) {
                            return null;
                        }

                        return (
                            <div
                                key={section.name}
                                className={`
                                    bg-blue-800/40 ${minimized && open ? 'p-1 flex flex-col items-center' : 'p-3'} shadow-inner border border-blue-600/50 rounded-lg
                                    ${open ? 'ml-0 mr-0' : 'ml-auto mr-auto'} 
                                    ${index === 0 ? '' : minimized && open ? 'mt-2' : 'mt-4'}
                                `}
                            >
                                {open && !minimized && (
                                    <h3 className="text-blue-200 text-xs font-semibold uppercase tracking-wider mb-3 px-1 pt-0 font-poppins">
                                        {section.name}
                                    </h3>
                                )}
                                <div className="space-y-1">
                                    {filteredItems.map(({ to, label, icon, hasDropdown, subItems }) => (
                                        <div key={to}>
                                            {hasDropdown ? (
                                                <div>
                                                    <button
                                                        onClick={() => toggleDropdown(label)}
                                                        className={`flex items-center ${minimized && open ? 'justify-center w-12 h-12 mx-auto my-1 rounded-lg' : 'justify-between w-full px-3 py-2 rounded-md'} text-sm font-medium transition-colors duration-200 group
                                                        text-blue-200 hover:bg-blue-700 hover:text-white
                                                        ${minimized && open ? 'hover:bg-blue-700/60' : ''} whitespace-nowrap font-inter`}
                                                        title={minimized && open ? label : undefined}
                                                    >
                                                        <div className={`flex items-center ${minimized && open ? 'justify-center w-full' : 'space-x-3'}`}>
                                                            {React.cloneElement(icon, {
                                                                className: minimized && open
                                                                    ? 'w-6 h-6 text-orange-300 group-hover:text-orange-200 mx-auto'
                                                                    : 'w-5 h-5 text-orange-300 group-hover:text-orange-200'
                                                            })}
                                                            {open && !minimized && <span>{label}</span>}
                                                        </div>
                                                        {open && !minimized && (
                                                            openDropdowns[label] ? 
                                                            <ChevronDownIcon className="w-4 h-4" /> : 
                                                            <ChevronRightIcon className="w-4 h-4" />
                                                        )}
                                                    </button>
                                                    {openDropdowns[label] && open && !minimized && subItems && (
                                                        <div className="ml-4 mt-2 space-y-1">
                                                            {subItems.map(({ to: subTo, label: subLabel, icon: subIcon }) => (
                                                                <NavLink
                                                                    key={subTo}
                                                                    to={subTo}
                                                                    onClick={handleNavLinkClick}
                                                                >
                                                                    {({ isActive }) => {
                                                                        const linkIsActive = isActive || location.pathname.startsWith(subTo + '/');
                                                                        return (
                                                                            <span
                                                                                className={`flex items-center space-x-3 px-3 py-2 text-sm font-medium transition-colors duration-200 group rounded-md
                                                                                ${linkIsActive
                                                                                    ? 'bg-orange-600 text-white shadow-md'
                                                                                    : 'text-blue-200 hover:bg-blue-700 hover:text-white'
                                                                                } whitespace-nowrap font-inter`}
                                                                            >
                                                                                {React.cloneElement(subIcon, {
                                                                                    className: `w-4 h-4 ${linkIsActive ? 'text-white' : 'text-orange-300 group-hover:text-orange-200'}`
                                                                                })}
                                                                                <span>{subLabel}</span>
                                                                            </span>
                                                                        );
                                                                    }}
                                                                </NavLink>
                                                            ))}
                                                        </div>
                                                    )}
                                                </div>
                                            ) : (
                                                <NavLink
                                                    to={to}
                                                    onClick={handleNavLinkClick}
                                                    title={minimized && open ? label : undefined}
                                                >
                                                    {({ isActive }) => { 
                                                        const linkIsActive = isActive || location.pathname.startsWith(to + '/');
                                                        return (
                                                            <span
                                                                className={`flex items-center ${minimized && open ? 'justify-center w-12 h-12 mx-auto my-1 rounded-sm' : 'space-x-3 px-3 py-2'} text-sm font-medium transition-colors duration-200 group
                                                                ${linkIsActive
                                                                    ? 'bg-orange-600 text-white shadow-md'
                                                                    : 'text-blue-200 hover:bg-blue-700 hover:text-white'}
                                                                ${minimized && open ? 'hover:bg-blue-700/60' : ''} whitespace-nowrap font-inter`}
                                                            >
                                                                {React.cloneElement(icon, {
                                                                    className: minimized && open
                                                                        ? `w-6 h-6 ${linkIsActive ? 'text-white' : 'text-orange-300 group-hover:text-orange-200'} mx-auto`
                                                                        : `w-5 h-5 ${linkIsActive ? 'text-white' : 'text-orange-300 group-hover:text-orange-200'}`
                                                                })}
                                                                {open && !minimized && <span>{label}</span>}
                                                            </span>
                                                        );
                                                    }}
                                                </NavLink>
                                            )}
                                        </div>
                                    ))}
                                </div>
                            </div>
                        );
                    })}
                </nav>

                {/* Footer */}
                {open && !minimized && (
                    <div className="px-4 py-3 border-t border-blue-700/50">
                        <p className="text-xs text-blue-300 font-inter">
                            Citizen Portal Admin v1.0
                        </p>
                    </div>
                )}
            </div>

            {/* Mobile overlay */}
            {isMobile && open && (
                <div
                    className="fixed inset-0 bg-black opacity-50 z-40"
                    onClick={onClose}
                ></div>
            )}
        </>
    );
}