import { useState, useEffect, useRef } from 'react';
import { Routes, Route, Link, useLocation, useNavigate } from 'react-router-dom';
import {
    LayoutDashboard, CreditCard, Send, History, LogOut, Menu, X,
    Users, Settings, TrendingUp, ArrowDownCircle, BarChart2,
    StickyNote, Activity, Shield, Bell, Zap, Globe2,
    Banknote, ChevronRight, Check, UserCircle
} from 'lucide-react';
import Overview from './Overview';
import TransferMoney from './TransferMoney';
import TransactionsHistory from './TransactionsHistory';
import CardsView from './CardsView';
import LoanView from './LoanView';
import TopupView from './TopupView';
import PaymentsView from './PaymentsView';
import CurrencyView from './CurrencyView';
import ProfileView from './ProfileView';
import AdminPanel from './AdminPanel';
import AdminUsers from './AdminUsers';
import AdminTransactions from './AdminTransactions';
import AdminCards from './AdminCards';
import AdminNotes from './AdminNotes';
import AdminSettings from './AdminSettings';
import AdminLogs from './AdminLogs';
import { useNotifications } from '../../context/NotificationsContext';

const SidebarLink = ({ to, icon: Icon, label, isActive, onClick }) => (
    <Link to={to} onClick={onClick}
        className={`flex items-center gap-3 px-4 py-2.5 rounded-xl transition-all duration-200 ${isActive
            ? 'bg-blue-gradient text-primary shadow-md scale-[1.01]'
            : 'text-dimWhite hover:bg-white/5 hover:text-white'}`}>
        <Icon className="w-4 h-4 flex-shrink-0" />
        <span className="font-poppins font-medium text-sm">{label}</span>
    </Link>
);

const SidebarSection = ({ label, children }) => (
    <div className="mt-3">
        <div className="text-dimWhite/40 text-[10px] font-poppins uppercase tracking-widest px-4 py-1.5">{label}</div>
        <div className="flex flex-col gap-0.5">{children}</div>
    </div>
);

const NotificationDropdown = ({ onClose }) => {
    const { notifications, markRead, markAllRead, unreadCount } = useNotifications();
    const ref = useRef(null);

    useEffect(() => {
        const handler = (e) => { if (ref.current && !ref.current.contains(e.target)) onClose(); };
        document.addEventListener('mousedown', handler);
        return () => document.removeEventListener('mousedown', handler);
    }, [onClose]);

    const typeIcon = (t) => {
        if (t === 'success') return <div className="w-2 h-2 rounded-full bg-green-400 flex-shrink-0 mt-1" />;
        if (t === 'warning') return <div className="w-2 h-2 rounded-full bg-yellow-400 flex-shrink-0 mt-1" />;
        if (t === 'error')   return <div className="w-2 h-2 rounded-full bg-red-400 flex-shrink-0 mt-1" />;
        return <div className="w-2 h-2 rounded-full bg-blue-400 flex-shrink-0 mt-1" />;
    };

    return (
        <div ref={ref} className="absolute top-12 right-0 w-80 bg-[#0f0f1a] border border-gray-700/60 rounded-2xl shadow-2xl z-[100] overflow-hidden animate-fade-in">
            <div className="flex items-center justify-between px-4 py-3 border-b border-gray-800">
                <span className="text-white font-poppins font-semibold text-sm">Уведомления</span>
                {unreadCount > 0 && (
                    <button onClick={markAllRead} className="flex items-center gap-1 text-secondary text-xs font-poppins hover:underline">
                        <Check size={11}/> Прочитать все
                    </button>
                )}
            </div>
            <div className="max-h-80 overflow-y-auto divide-y divide-gray-800/50">
                {notifications.length === 0 ? (
                    <div className="py-8 text-center text-dimWhite font-poppins text-sm">Нет уведомлений</div>
                ) : notifications.slice(0, 20).map((n) => (
                    <div key={n.id} onClick={() => markRead(n.id)}
                        className={`flex items-start gap-3 px-4 py-3 cursor-pointer transition-colors ${n.is_read ? 'opacity-60' : 'hover:bg-white/5'}`}>
                        {typeIcon(n.type)}
                        <div className="flex-1 min-w-0">
                            <p className="text-white text-xs font-poppins font-medium truncate">{n.title}</p>
                            <p className="text-dimWhite text-xs font-poppins truncate">{n.message}</p>
                            <p className="text-dimWhite/50 text-[10px] font-poppins mt-0.5">
                                {n.created_at ? new Date(n.created_at).toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' }) : 'только что'}
                            </p>
                        </div>
                        {!n.is_read && <div className="w-1.5 h-1.5 rounded-full bg-secondary flex-shrink-0 mt-1.5" />}
                    </div>
                ))}
            </div>
        </div>
    );
};

const DashboardLayout = () => {
    const [isSidebarOpen, setIsSidebarOpen] = useState(false);
    const [showNotifications, setShowNotifications] = useState(false);
    const location = useLocation();
    const navigate = useNavigate();
    const { unreadCount } = useNotifications();

    const userStr = localStorage.getItem('iosco_user');
    const user = userStr ? JSON.parse(userStr) : null;
    const isAdmin = user?.role === 'admin';

    useEffect(() => { setIsSidebarOpen(false); }, [location.pathname]);

    const isActive = (path, exact = false) =>
        exact ? location.pathname === path : location.pathname.startsWith(path);

    const handleLogout = () => {
        localStorage.removeItem('iosco_token');
        localStorage.removeItem('iosco_user');
        navigate('/');
    };

    const bottomNav = [
        { to: '/dashboard', icon: LayoutDashboard, label: 'Главная', exact: true },
        { to: '/dashboard/cards', icon: CreditCard, label: 'Карты' },
        { to: '/dashboard/transfer', icon: Send, label: 'Перевод' },
        { to: '/dashboard/payments', icon: Zap, label: 'Платежи' },
        { to: '/dashboard/history', icon: History, label: 'История' },
    ];

    return (
        <div className="min-h-screen bg-primary flex overflow-hidden">
            {/* Мобильная шапка */}
            <div className="md:hidden fixed top-0 w-full bg-black-gradient-2 z-50 px-4 py-3.5 border-b border-gray-800 flex justify-between items-center shadow-md">
                <h1 className="text-white font-poppins font-bold text-lg tracking-wide">IOSCO<span className="text-secondary">.</span></h1>
                <div className="flex items-center gap-2">
                    <div className="relative">
                        <button onClick={() => setShowNotifications(v => !v)}
                            className="relative p-2 rounded-xl bg-white/5 text-dimWhite hover:text-white transition-colors">
                            <Bell size={18} />
                            {unreadCount > 0 && (
                                <span className="absolute -top-0.5 -right-0.5 min-w-[16px] h-4 rounded-full bg-red-500 text-white text-[9px] font-bold flex items-center justify-center px-0.5">
                                    {unreadCount > 9 ? '9+' : unreadCount}
                                </span>
                            )}
                        </button>
                        {showNotifications && <NotificationDropdown onClose={() => setShowNotifications(false)} />}
                    </div>
                    <button className="text-white p-2 rounded-lg bg-white/5 transition-transform active:scale-90" onClick={() => setIsSidebarOpen(!isSidebarOpen)}>
                        {isSidebarOpen ? <X size={22} /> : <Menu size={22} />}
                    </button>
                </div>
            </div>

            {isSidebarOpen && (
                <div className="md:hidden fixed inset-0 bg-black/50 z-40 backdrop-blur-sm" onClick={() => setIsSidebarOpen(false)} />
            )}

            {/* Sidebar */}
            <aside className={`fixed md:static inset-y-0 left-0 bg-black-gradient-2 border-r border-gray-800 transform transition-transform duration-300 z-50 shadow-xl
                ${isSidebarOpen ? 'translate-x-0' : '-translate-x-full'} md:translate-x-0 overflow-y-auto flex-shrink-0`}
                style={{ width: '240px', minWidth: '240px' }}>
                <div className="p-4 h-full flex flex-col">
                    <Link to="/" className="mt-2 mb-5 md:mt-5 inline-block">
                        <h1 className="text-white font-poppins font-bold text-xl tracking-wide">
                            IOSCO Bank<span className="text-secondary text-2xl leading-5">.</span>
                        </h1>
                    </Link>

                    {user && (
                        <div className="flex items-center gap-3 px-3 py-3 bg-black/30 rounded-xl mb-3 border border-gray-800">
                            <div className="w-9 h-9 rounded-full bg-blue-gradient flex items-center justify-center text-primary font-bold text-sm flex-shrink-0">
                                {user.full_name?.[0]?.toUpperCase() || user.username?.[0]?.toUpperCase() || '?'}
                            </div>
                            <div className="overflow-hidden">
                                <div className="text-white text-xs font-poppins font-semibold truncate">{user.full_name || user.username}</div>
                                <div className="text-dimWhite text-xs font-poppins">{user.role === 'admin' ? 'Администратор' : 'Клиент'}</div>
                            </div>
                        </div>
                    )}

                    <nav className="flex-1 flex flex-col gap-0.5">
                        <SidebarSection label="Банкинг">
                            <SidebarLink to="/dashboard" icon={LayoutDashboard} label="Главная" isActive={isActive('/dashboard', true)} onClick={() => setIsSidebarOpen(false)} />
                            <SidebarLink to="/dashboard/cards" icon={CreditCard} label="Мои карты" isActive={isActive('/dashboard/cards')} onClick={() => setIsSidebarOpen(false)} />
                            <SidebarLink to="/dashboard/transfer" icon={Send} label="Перевод" isActive={isActive('/dashboard/transfer')} onClick={() => setIsSidebarOpen(false)} />
                            <SidebarLink to="/dashboard/topup" icon={ArrowDownCircle} label="Пополнить" isActive={isActive('/dashboard/topup')} onClick={() => setIsSidebarOpen(false)} />
                            <SidebarLink to="/dashboard/loans" icon={TrendingUp} label="Кредиты" isActive={isActive('/dashboard/loans')} onClick={() => setIsSidebarOpen(false)} />
                            <SidebarLink to="/dashboard/payments" icon={Zap} label="Платежи" isActive={isActive('/dashboard/payments')} onClick={() => setIsSidebarOpen(false)} />
                            <SidebarLink to="/dashboard/currency" icon={Globe2} label="Валюта" isActive={isActive('/dashboard/currency')} onClick={() => setIsSidebarOpen(false)} />
                            <SidebarLink to="/dashboard/history" icon={History} label="История" isActive={isActive('/dashboard/history')} onClick={() => setIsSidebarOpen(false)} />
                            <SidebarLink to="/dashboard/profile" icon={UserCircle} label="Профиль" isActive={isActive('/dashboard/profile')} onClick={() => setIsSidebarOpen(false)} />
                        </SidebarSection>

                        {isAdmin && (
                            <SidebarSection label="Администрирование">
                                <SidebarLink to="/dashboard/admin" icon={BarChart2} label="Дашборд" isActive={isActive('/dashboard/admin', true)} onClick={() => setIsSidebarOpen(false)} />
                                <SidebarLink to="/dashboard/admin/users" icon={Users} label="Пользователи" isActive={isActive('/dashboard/admin/users')} onClick={() => setIsSidebarOpen(false)} />
                                <SidebarLink to="/dashboard/admin/transactions" icon={Activity} label="Транзакции" isActive={isActive('/dashboard/admin/transactions')} onClick={() => setIsSidebarOpen(false)} />
                                <SidebarLink to="/dashboard/admin/cards" icon={Shield} label="Все карты" isActive={isActive('/dashboard/admin/cards')} onClick={() => setIsSidebarOpen(false)} />
                                <SidebarLink to="/dashboard/admin/notes" icon={StickyNote} label="Заметки" isActive={isActive('/dashboard/admin/notes')} onClick={() => setIsSidebarOpen(false)} />
                                <SidebarLink to="/dashboard/admin/settings" icon={Settings} label="Настройки" isActive={isActive('/dashboard/admin/settings')} onClick={() => setIsSidebarOpen(false)} />
                                <SidebarLink to="/dashboard/admin/logs" icon={Activity} label="Журнал" isActive={isActive('/dashboard/admin/logs')} onClick={() => setIsSidebarOpen(false)} />
                            </SidebarSection>
                        )}
                    </nav>

                    <div className="relative mt-3">
                        <button onClick={() => setShowNotifications(v => !v)}
                            className="hidden md:flex w-full items-center gap-3 px-4 py-2.5 rounded-xl text-dimWhite hover:bg-white/5 hover:text-white transition-all">
                            <Bell className="w-4 h-4 flex-shrink-0" />
                            <span className="font-poppins font-medium text-sm flex-1 text-left">Уведомления</span>
                            {unreadCount > 0 && (
                                <span className="min-w-[18px] h-[18px] rounded-full bg-red-500 text-white text-[10px] font-bold flex items-center justify-center px-1">
                                    {unreadCount > 9 ? '9+' : unreadCount}
                                </span>
                            )}
                        </button>
                        {showNotifications && <div className="absolute bottom-full left-0 right-0 mb-1"><NotificationDropdown onClose={() => setShowNotifications(false)} /></div>}
                    </div>

                    <button onClick={handleLogout}
                        className="flex items-center gap-3 px-4 py-2.5 rounded-xl text-dimWhite hover:bg-red-500/10 hover:text-red-400 transition-all mt-1">
                        <LogOut className="w-4 h-4" />
                        <span className="font-poppins font-medium text-sm">Выйти</span>
                    </button>
                </div>
            </aside>

            {/* Основной контент */}
            <main className="flex-1 h-screen overflow-y-auto w-full text-white font-poppins relative min-w-0">
                <div className="absolute z-[0] w-[40%] h-[35%] top-0 right-0 pink__gradient opacity-30 pointer-events-none" />
                <div className="absolute z-[0] w-[50%] h-[50%] top-1/2 left-0 blue__gradient opacity-15 pointer-events-none" />

                <div className="relative z-[1] w-full max-w-6xl mx-auto p-4 md:p-7 mt-14 md:mt-0 pb-28 md:pb-10">
                    <Routes>
                        <Route path="/" element={<Overview />} />
                        <Route path="/cards" element={<CardsView />} />
                        <Route path="/transfer" element={<TransferMoney />} />
                        <Route path="/topup" element={<TopupView />} />
                        <Route path="/loans" element={<LoanView />} />
                        <Route path="/payments" element={<PaymentsView />} />
                        <Route path="/currency" element={<CurrencyView />} />
                        <Route path="/history" element={<TransactionsHistory />} />
                        <Route path="/profile" element={<ProfileView />} />
                        {isAdmin && (
                            <>
                                <Route path="/admin" element={<AdminPanel />} />
                                <Route path="/admin/users" element={<AdminUsers />} />
                                <Route path="/admin/transactions" element={<AdminTransactions />} />
                                <Route path="/admin/cards" element={<AdminCards />} />
                                <Route path="/admin/notes" element={<AdminNotes />} />
                                <Route path="/admin/settings" element={<AdminSettings />} />
                                <Route path="/admin/logs" element={<AdminLogs />} />
                            </>
                        )}
                    </Routes>
                </div>
            </main>

            {/* Нижняя мобильная навигация */}
            <nav className="md:hidden fixed bottom-0 left-0 right-0 z-50 bg-[#0a0a14]/95 backdrop-blur-xl border-t border-gray-800/60 pb-safe">
                <div className="flex items-center justify-around px-2 py-2">
                    {bottomNav.map(({ to, icon: Icon, label, exact }) => {
                        const active = exact ? location.pathname === to : location.pathname.startsWith(to);
                        return (
                            <Link key={to} to={to}
                                className={`flex flex-col items-center gap-0.5 px-3 py-1.5 rounded-xl transition-all ${active ? 'text-secondary' : 'text-dimWhite hover:text-white'}`}>
                                <div className={`p-1.5 rounded-xl transition-all ${active ? 'bg-secondary/15' : ''}`}>
                                    <Icon size={20} className={active ? 'text-secondary' : ''} strokeWidth={active ? 2.5 : 1.8} />
                                </div>
                                <span className={`text-[10px] font-poppins font-medium ${active ? 'text-secondary' : ''}`}>{label}</span>
                            </Link>
                        );
                    })}
                </div>
            </nav>
        </div>
    );
};

export default DashboardLayout;
