import React, { useState, useEffect } from 'react';
import { NavLink } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import axios from 'axios';
import {
    LayoutDashboard,
    Receipt,
    Wallet,
    FileText,
    Users,
    Settings,
    PlusCircle,
    BarChart3,
    Clock,
    Briefcase,
    History,
    CreditCard,
    User,
    RefreshCw,
    PieChart,
    Tag,
    DollarSign,
    ChevronLeft,
    ChevronRight,
    Lock,
    UserCog
} from 'lucide-react';

const Sidebar = ({ isCollapsed, setIsCollapsed, isMobile }) => {
    const { user } = useAuth();
    const isAdmin = user?.role !== 'CLIENT';
    const [metrics, setMetrics] = useState(null);
    const [companyName, setCompanyName] = useState('FinancePro');
    const [companyLogo, setCompanyLogo] = useState(null);

    useEffect(() => {
        if (isAdmin) {
            const fetchMetrics = async () => {
                try {
                    const res = await axios.get('http://localhost:5000/api/dashboard/metrics', {
                        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
                    });
                    setMetrics(res.data);
                } catch (err) {
                    console.error('Failed to fetch sidebar metrics', err);
                }
            };
            fetchMetrics();
        }
    }, [isAdmin]);

    useEffect(() => {
        const fetchSettings = async () => {
            try {
                const settingsService = await import('../services/settingsService');
                const res = await settingsService.default.getSettings();
                setCompanyName(res.data.COMPANY_NAME || 'FinancePro');
                setCompanyLogo(res.data.COMPANY_LOGO || null);
            } catch (err) {
                console.error('Failed to fetch company settings', err);
            }
        };
        fetchSettings();
    }, []);

    const billingStatus = 'Active';

    const adminMenu = [
        {
            group: 'MAIN', items: [
                { name: 'Dashboard', icon: LayoutDashboard, path: '/dashboard' },
                { name: 'Income', icon: PlusCircle, path: '/income' },
                { name: 'Expenses', icon: Wallet, path: '/expenses' },
                { name: 'Vendors', icon: Briefcase, path: '/vendors' },
                {
                    name: 'Invoices',
                    icon: Receipt,
                    path: '/invoices',
                    badge: metrics?.billing?.overdue > 0 ? metrics.billing.overdue : null,
                    badgeColor: 'bg-rose-500'
                },
                { name: 'Quotes', icon: FileText, path: '/quotes' },
            ]
        },
        {
            group: 'MANAGEMENT', items: [
                { name: 'Clients', icon: Users, path: '/clients' },
                {
                    name: 'Subscriptions',
                    icon: RefreshCw,
                    path: '/subscriptions',
                    badge: metrics?.metrics?.subscriptionCount > 0 ? metrics.metrics.subscriptionCount : null
                },
                { name: 'Payroll', icon: Briefcase, path: '/payroll', isPremium: true },
                { name: 'Staff', icon: Users, path: '/staff' },
                { name: 'Staff Work', icon: Clock, path: '/staff-payments' },
                { name: 'CRM Automation', icon: RefreshCw, path: '/crm-automation' },
                { name: 'System Users', icon: UserCog, path: '/users' },
            ]
        },
        {
            group: 'FINANCIALS', items: [
                { name: 'Banking', icon: CreditCard, path: '/banking' },
                { name: 'Budgets', icon: Clock, path: '/budgets', isPremium: true },
                { name: 'Payment Categories', icon: Tag, path: '/categories' }, // Added link
                { name: 'Reports', icon: BarChart3, path: '/reports/profit-loss' },
            ]
        }
    ];

    const clientMenu = [
        {
            group: 'PORTAL', items: [
                { name: 'Dashboard', icon: LayoutDashboard, path: '/portal/dashboard' },
                { name: 'My Invoices', icon: Receipt, path: '/portal/invoices' },
                { name: 'Payments', icon: History, path: '/portal/payments' },
                { name: 'Profile', icon: User, path: '/portal/profile' },
            ]
        }
    ];

    const sections = isAdmin ? adminMenu : clientMenu;

    return (
        <aside
            className={`fixed inset-y-0 left-0 z-[40] bg-white dark:bg-bg-dark text-slate-500 dark:text-slate-400 flex flex-col border-r border-slate-200 dark:border-slate-800 transition-all duration-300 ease-in-out 
                ${isMobile ? (isCollapsed ? '-translate-x-full shadow-none' : 'translate-x-0 shadow-2xl') : 'translate-x-0'}
                ${isCollapsed ? 'w-20' : 'w-72'}`}
        >
            <div className={`flex flex-col items-center justify-center transition-all duration-300 ${isCollapsed ? 'p-4 gap-0' : 'p-8 gap-4'}`}>
                <div className="relative group shrink-0">
                    {companyLogo ? (
                        <img
                            src={companyLogo.startsWith('http') ? companyLogo : `http://localhost:5000${companyLogo}`}
                            alt={companyName}
                            className={`transition-all duration-300 ${isCollapsed ? 'w-10 h-10' : 'w-auto h-20 max-w-[180px]'} object-contain`}
                        />
                    ) : (
                        <div className={`bg-gradient-to-br from-primary to-primary-dark rounded-2xl flex items-center justify-center font-black text-white shrink-0 shadow-xl shadow-primary/20 transition-all duration-300 ${isCollapsed ? 'w-10 h-10 text-base' : 'w-16 h-16 text-2xl'}`}>
                            {companyName.charAt(0)}
                        </div>
                    )}
                    <div className="absolute -inset-2 bg-primary/5 rounded-full scale-0 group-hover:scale-100 transition-transform duration-500"></div>
                </div>
            </div>

            <nav className="flex-1 px-4 mt-2 space-y-6 overflow-y-auto custom-scrollbar pb-8">
                {sections.map((section) => (
                    <div key={section.group} className="space-y-1">
                        {!isCollapsed && (
                            <h3 className="px-4 text-[11px] font-black text-slate-400 dark:text-slate-600 uppercase tracking-[0.2em] mb-2 pl-4">
                                {section.group}
                            </h3>
                        )}
                        {section.items.map((item) => {
                            const isLocked = item.isPremium && billingStatus === 'Locked' && !isAdmin;

                            if (isLocked) {
                                return (
                                    <div
                                        key={item.name}
                                        className={`flex items-center justify-between px-4 py-3 rounded-2xl text-sm font-semibold opacity-30 cursor-not-allowed group relative transition-all ${isCollapsed ? 'justify-center' : ''
                                            }`}
                                        title="Upgrade required"
                                    >
                                        <div className="flex items-center gap-4">
                                            <item.icon className="w-5 h-5 shrink-0" />
                                            {!isCollapsed && <span>{item.name}</span>}
                                        </div>
                                        {!isCollapsed && <Lock className="w-3.5 h-3.5 text-amber-500" />}
                                    </div>
                                );
                            }

                            return (
                                <NavLink
                                    key={item.name}
                                    to={item.path}
                                    title={isCollapsed ? item.name : ''}
                                    className={({ isActive }) => `
                                        flex items-center justify-between px-4 py-3 rounded-2xl text-[14px] font-semibold transition-all group relative
                                        ${isActive
                                            ? 'bg-primary/10 text-primary active-nav'
                                            : 'hover:bg-slate-50 dark:hover:bg-slate-800/50 hover:text-slate-900 dark:hover:text-white'}
                                        ${isCollapsed ? 'justify-center px-0' : ''}
                                    `}
                                >
                                    <div className="flex items-center gap-4">
                                        <item.icon className={`w-5 h-5 transition-all shrink-0 
                                            ${isCollapsed ? '' : ''} 
                                            group-[.active-nav]:scale-110 group-hover:scale-110`}
                                        />
                                        <span className={`transition-all duration-300 whitespace-nowrap overflow-hidden ${isCollapsed ? 'opacity-0 w-0' : 'opacity-100 w-auto'}`}>
                                            {item.name}
                                        </span>
                                    </div>

                                    {!isCollapsed && item.badge && (
                                        <span className={`${item.badgeColor || 'bg-primary'} text-[10px] text-white px-2 py-0.5 rounded-full font-black shadow-lg shadow-primary/10`}>
                                            {item.badge}
                                        </span>
                                    )}

                                    {isCollapsed && item.badge && (
                                        <div className={`absolute top-2 right-2 w-2.5 h-2.5 rounded-full ${item.badgeColor || 'bg-primary'} border-2 border-white dark:border-bg-dark`} />
                                    )}

                                    {/* Active Indicator Bar */}
                                    <div className={`absolute right-0 top-1/2 -translate-y-1/2 w-1.5 h-0 bg-primary rounded-l-full transition-all duration-300 group-[.active-nav]:h-8`} />
                                </NavLink>
                            );
                        })}
                    </div>
                ))}
            </nav>

            <div className="p-4 border-t border-slate-100 dark:border-slate-800 space-y-2 mt-auto">
                <NavLink
                    to="/settings"
                    title={isCollapsed ? 'Settings' : ''}
                    className={({ isActive }) => `
                        flex items-center gap-4 px-4 py-3 rounded-2xl text-[14px] font-semibold transition-all group relative
                        ${isActive ? 'bg-primary/10 text-primary active-nav' : 'hover:bg-slate-50 dark:hover:bg-slate-800/50 hover:text-slate-900 dark:hover:text-white'}
                        ${isCollapsed ? 'justify-center px-0' : ''}
                    `}
                >
                    <Settings className="w-5 h-5 group-hover:rotate-45 transition-transform" />
                    <span className={`transition-all duration-300 whitespace-nowrap overflow-hidden ${isCollapsed ? 'opacity-0 w-0' : 'opacity-100 w-auto'}`}>
                        Settings
                    </span>
                    <div className={`absolute right-0 top-1/2 -translate-y-1/2 w-1.5 h-0 bg-primary rounded-l-full transition-all duration-300 group-[.active-nav]:h-8`} />
                </NavLink>

                <button
                    onClick={() => setIsCollapsed(!isCollapsed)}
                    className="w-full flex items-center px-4 py-3 rounded-2xl text-[14px] font-semibold hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-all text-slate-400 group"
                >
                    <div className={`flex items-center w-full transition-all duration-300 ${isCollapsed ? 'justify-center' : 'gap-4'}`}>
                        {isCollapsed ? <ChevronRight className="w-5 h-5 group-hover:translate-x-1 transition-transform" /> : (
                            <>
                                <ChevronLeft className="w-5 h-5 group-hover:-translate-x-1 transition-transform" />
                                <span>Collapse</span>
                            </>
                        )}
                    </div>
                </button>
            </div>
        </aside>
    );
};

export default Sidebar;
