import React from 'react';
import { NavLink, useLocation } from 'react-router-dom';
import {
    Home,
    Settings,
    Shield,
    UserCog,
    Key,
    LogOut,
    ChevronDown,
    ChevronLeft,
    Package,
    FolderOpen,
    Sliders,
    BadgePercent,
    ShoppingCart,
    Users,
    Truck,
    X,
    MessageSquare,
    CreditCard,
    Wallet,
    BarChart3,
    FileText,
    TrendingUp,
    Bell,
    DollarSign,
    TrendingDown,
    Warehouse
} from 'lucide-react';
import { useAuth } from '../../contexts/AuthContext';
import { PermissionWrapper } from '../common/PermissionWrapper';
import { SectionTitle, SmallText } from '../ui/Typography';

interface MenuItem {
    title: string;
    icon: any;
    path?: string;
    permission?: number;
    children?: MenuItem[];
    exact?: boolean;
}

const menuItems: MenuItem[] = [
    {
        title: 'داشبورد',
        icon: Home,
        path: '/',
    },
    {
        title: 'سفارشات',
        icon: ShoppingCart,
        path: '/orders',
    },
    {
        title: 'مدیریت کاربران',
        icon: Users,
        path: '/users-admin',
    },
    {
        title: 'کدهای تخفیف',
        icon: BadgePercent,
        path: '/discount-codes',
    },
    {
        title: 'اعلانات ادمین',
        icon: Bell,
        path: '/admin-notifications',
    },
    {
        title: 'پیام‌های تماس با ما',
        icon: FileText,
        path: '/contact-us',
    },
    {
        title: 'مدیریت محصولات',
        icon: Package,
        children: [
            {
                title: 'محصولات',
                icon: Package,
                path: '/products',
            },
            {
                title: 'دسته‌بندی‌ها',
                icon: FolderOpen,
                path: '/categories',
            },
            {
                title: 'گزینه‌های محصول',
                icon: Sliders,
                path: '/product-options',
            },
            {
                title: 'نظرات محصولات',
                icon: MessageSquare,
                path: '/products/comments',
            },
        ]
    },
    {
        title: 'گزارش‌ها',
        icon: BarChart3,
        children: [
            {
                title: 'گزارش کدهای تخفیف',
                icon: BadgePercent,
                path: '/reports/discount-usage',
            },
            {
                title: 'گزارش کاربر و کد تخفیف',
                icon: Users,
                path: '/reports/customer-discount-usage',
            },
            {
                title: 'گزارش روش‌های پرداخت',
                icon: CreditCard,
                path: '/reports/payment-methods',
            },
            {
                title: 'گزارش ارسال‌ها',
                icon: Truck,
                path: '/reports/shipments-by-method',
            },
            {
                title: 'گزارش خلاصه فروش',
                icon: DollarSign,
                path: '/reports/sales-summary',
            },
            {
                title: 'گزارش سود و زیان',
                icon: TrendingDown,
                path: '/reports/profit-loss',
            },
            {
                title: 'گزارش ارزش موجودی',
                icon: Warehouse,
                path: '/reports/inventory-value',
            },
            {
                title: 'گزارش مقایسه Variant',
                icon: TrendingUp,
                path: '/reports/variant-comparison',
            },
        ]
    },
    {
        title: 'مدیریت سیستم',
        icon: Settings,
        children: [
            {
                title: 'نقش‌ها',
                icon: Shield,
                path: '/roles',
                permission: 22,
            },
            {
                title: 'کاربران ادمین',
                icon: UserCog,
                path: '/admin-users',
                permission: 22,
            },
            {
                title: 'دسترسی‌ها',
                icon: Key,
                path: '/permissions',
                permission: 22,
            },
            {
                title: 'اسلایدر لندینگ',
                icon: Sliders,
                path: '/landing-hero',
            },
            {
                title: 'روش‌های ارسال',
                icon: Truck,
                path: '/shipping-methods',
            },
            {
                title: 'درگاه‌های پرداخت',
                icon: CreditCard,
                path: '/payment-ipg',
            },
            {
                title: 'پرداخت کارت به کارت',
                icon: CreditCard,
                path: '/payment-card',
            },
            {
                title: 'مدیریت کیف پول',
                icon: Wallet,
                path: '/wallet',
                exact: true,
            },
            {
                title: 'شارژ کیف پول',
                icon: Wallet,
                path: '/wallet/credit',
            },
            {
                title: 'تنظیمات سیستم',
                icon: Settings,
                path: '/system-settings',
            },
        ]
    }
];

interface SidebarProps {
    isOpen: boolean;
    onClose: () => void;
}

export const Sidebar = ({ isOpen, onClose }: SidebarProps) => {
    const { user, logout } = useAuth();
    const location = useLocation();
    const [expandedItems, setExpandedItems] = React.useState<string[]>(() => {
        // Load from localStorage on mount
        const saved = localStorage.getItem('sidebar_expanded_items');
        return saved ? JSON.parse(saved) : [];
    });

    // Auto-expand menu items based on current route
    React.useEffect(() => {
        const currentPath = location.pathname;

        setExpandedItems(prev => {
            const itemsToExpand: string[] = [];

            menuItems.forEach(item => {
                if (item.children) {
                    // Check if any child matches current path
                    const hasActiveChild = item.children.some(child => {
                        if (child.path) {
                            if (child.exact) {
                                return currentPath === child.path;
                            }
                            // For non-exact paths, check if current path starts with child path
                            // but also ensure it's not a partial match (e.g., /wallet should not match /wallet/credit)
                            if (currentPath === child.path) {
                                return true;
                            }
                            // Only match if current path starts with child path AND has a slash after it
                            // This prevents /wallet from matching /wallet/credit
                            return currentPath.startsWith(child.path + '/');
                        }
                        return false;
                    });

                    if (hasActiveChild && !prev.includes(item.title)) {
                        itemsToExpand.push(item.title);
                    }
                }
            });

            if (itemsToExpand.length > 0) {
                return [...prev, ...itemsToExpand];
            }
            return prev;
        });
    }, [location.pathname]);

    React.useEffect(() => {
        // Save to localStorage whenever expandedItems changes
        localStorage.setItem('sidebar_expanded_items', JSON.stringify(expandedItems));
    }, [expandedItems]);

    const toggleExpanded = (title: string) => {
        setExpandedItems(prev => {
            const newItems = prev.includes(title)
                ? prev.filter(item => item !== title)
                : [...prev, title];
            return newItems;
        });
    };

    const renderMenuItem = (item: MenuItem, depth = 0) => {
        const hasChildren = item.children && item.children.length > 0;
        const isExpanded = expandedItems.includes(item.title);
        const paddingLeft = depth * 16;

        if (hasChildren) {
            return (
                <div key={item.title} className="space-y-1">
                    <button
                        onClick={() => toggleExpanded(item.title)}
                        className={`w-full flex items-center px-4 py-3 text-sm font-medium rounded-xl transition-all duration-200
                            text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 hover:shadow-sm`}
                        style={{ paddingLeft: `${paddingLeft + 16}px` }}
                    >
                        <item.icon className="ml-3 h-5 w-5" />
                        <span className="flex-1 text-right">{item.title}</span>
                        {isExpanded ? (
                            <ChevronDown className="h-4 w-4" />
                        ) : (
                            <ChevronLeft className="h-4 w-4" />
                        )}
                    </button>
                    {isExpanded && item.children && (
                        <div className="space-y-1">
                            {item.children.map(child => renderMenuItem(child, depth + 1))}
                        </div>
                    )}
                </div>
            );
        }

        const menuContent = (
            <NavLink
                to={item.path!}
                end={item.exact}
                onClick={() => {
                    // Close mobile menu when clicking a link
                    if (window.innerWidth < 1024) {
                        onClose();
                    }
                }}
                className={({ isActive }) =>
                    `w-full flex items-center px-4 py-3 text-sm font-medium rounded-xl transition-all duration-200 ${isActive
                        ? 'bg-primary-50 dark:bg-primary-900 text-primary-600 dark:text-primary-400 shadow-sm'
                        : 'text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-gray-900 dark:hover:text-white hover:shadow-sm'
                    }`
                }
                style={{ paddingLeft: `${paddingLeft + 16}px` }}
            >
                <item.icon className="ml-3 h-5 w-5" />
                {item.title}
            </NavLink>
        );

        if (item.permission) {
            return (
                <PermissionWrapper key={item.title} permission={item.permission}>
                    {menuContent}
                </PermissionWrapper>
            );
        }

        return <div key={item.title}>{menuContent}</div>;
    };

    return (
        <>
            {/* Mobile overlay */}
            {isOpen && (
                <div
                    className="fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden"
                    onClick={onClose}
                />
            )}

            {/* Sidebar */}
            <div className={`
                fixed lg:static inset-y-0 right-0 z-50 
                w-64 transform transition-transform duration-300 ease-in-out
                lg:translate-x-0 lg:block
                ${isOpen ? 'translate-x-0' : 'translate-x-full lg:translate-x-0'}
                flex flex-col h-screen bg-white dark:bg-gray-800 border-l border-gray-200 dark:border-gray-700 shadow-lg lg:shadow-none
            `}>
                {/* Mobile close button */}
                <div className="lg:hidden flex justify-between items-center p-4 border-b border-gray-200 dark:border-gray-700 flex-shrink-0">
                    <SectionTitle>
                        پنل مدیریت
                    </SectionTitle>
                    <button
                        onClick={onClose}
                        className="p-2 rounded-xl hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
                    >
                        <X className="h-5 w-5 text-gray-600 dark:text-gray-400" />
                    </button>
                </div>

                {/* Logo - desktop only */}
                <div className="hidden lg:flex h-16 items-center justify-center border-b border-gray-200 dark:border-gray-700 flex-shrink-0">
                    <SectionTitle>
                        پنل مدیریت
                    </SectionTitle>
                </div>

                {/* Navigation - scrollable */}
                <nav className="flex-1 space-y-1 px-4 py-6 overflow-y-auto overflow-x-hidden sidebar-nav min-h-0">
                    {menuItems.map(item => renderMenuItem(item))}
                </nav>

                {/* User Info - fixed at bottom */}
                <div className="border-t border-gray-200 dark:border-gray-700 p-4 flex-shrink-0 bg-white dark:bg-gray-800">
                    <div className="flex items-center space-x-3 space-x-reverse">
                        <div className="h-8 w-8 rounded-full bg-primary-600 flex items-center justify-center">
                            <span className="text-sm font-medium text-white">
                                {user?.first_name?.[0]}{user?.last_name?.[0]}
                            </span>
                        </div>
                        <div className="flex-1 min-w-0">
                            <SmallText>
                                {user?.first_name} {user?.last_name}
                            </SmallText>
                            <SmallText>
                                {user?.username}
                            </SmallText>
                        </div>
                        <button
                            onClick={logout}
                            className="text-gray-500 hover:text-red-600 dark:text-gray-400 dark:hover:text-red-400"
                        >
                            <LogOut className="h-5 w-5" />
                        </button>
                    </div>
                </div>
            </div>
        </>
    );
}; 