import React, { useState } from 'react';
import { Outlet, Link, useNavigate, useLocation } from 'react-router-dom';
import { useUser } from '../../context/UserContext';
import { useTheme } from '../../context/ThemeContext';
import axios from 'axios';

export default function AppLayout() {
    const { user, logout } = useUser();
    const { theme, toggleTheme } = useTheme();
    const isDarkMode = theme === 'dark';
    const navigate = useNavigate();
    const location = useLocation();
    const [isSidebarOpen, setIsSidebarOpen] = useState(true);
    const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);

    // Cerrar menú móvil al cambiar de ruta
    React.useEffect(() => {
        setIsMobileMenuOpen(false);
    }, [location.pathname]);

    const handleLogout = async () => {
        try {
            const token = localStorage.getItem('token');
            if (token) {
                await axios.post('/logout', {}, {
                    headers: { Authorization: `Bearer ${token}` }
                });
            }
        } catch (error) {
            console.error('Error en logout:', error);
        } finally {
            logout();
            navigate('/login');
        }
    };

    const menuItems = [
        { path: '/dashboard', icon: '📊', label: 'Dashboard', color: 'from-blue-500 to-cyan-500' },
        { path: '/pacientes', icon: '👥', label: 'Pacientes', color: 'from-green-500 to-emerald-500' },
        { path: '/citas', icon: '📅', label: 'Citas', color: 'from-purple-500 to-pink-500' },
        { path: '/historias-clinicas', icon: '📋', label: 'Historias Clínicas', color: 'from-orange-500 to-red-500' },
        { path: '/recetas', icon: '💊', label: 'Recetas Médicas', color: 'from-teal-500 to-cyan-500' },
        { path: '/categorias', icon: '📁', label: 'Categorías', color: 'from-cyan-500 to-blue-500' },
        { path: '/examenes', icon: '🔬', label: 'Exámenes', color: 'from-indigo-500 to-blue-500' },
        { path: '/vacunas', icon: '💉', label: 'Vacunas', color: 'from-pink-500 to-rose-500' },
        { path: '/facturacion', icon: '💳', label: 'Facturación', color: 'from-amber-500 to-yellow-500' },
        { path: '/usuarios', icon: '👤', label: 'Usuarios', color: 'from-violet-500 to-purple-500' },
    ];

    const isActive = (path: string) => location.pathname === path;

    return (
        <div className={`min-h-screen ${isDarkMode ? 'bg-gradient-to-br from-gray-900 via-slate-900 to-zinc-900' : 'bg-gradient-to-br from-gray-50 via-blue-50 to-cyan-50'}`}>
            {/* Header */}
            <header className={`fixed top-0 left-0 right-0 z-50 ${isDarkMode ? 'bg-gray-900/95 border-gray-700/50' : 'bg-white/95 border-gray-200/50'} backdrop-blur-lg border-b shadow-lg transition-all duration-300`}>
                <div className="flex items-center justify-between px-4 lg:px-6 py-3 lg:py-4">
                    {/* Logo & Menu Toggle */}
                    <div className="flex items-center gap-4">
                        {/* Mobile Menu Toggle */}
                        <button
                            onClick={() => setIsMobileMenuOpen(true)}
                            className={`lg:hidden p-2 rounded-xl transition-all ${isDarkMode ? 'hover:bg-gray-800 text-gray-200' : 'hover:bg-gray-100 text-gray-700'}`}
                        >
                            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
                            </svg>
                        </button>

                        {/* Desktop Sidebar Toggle */}
                        <button
                            onClick={() => setIsSidebarOpen(!isSidebarOpen)}
                            className={`hidden lg:block p-2 rounded-xl transition-all hover:scale-110 ${isDarkMode ? 'hover:bg-gray-800 text-gray-200' : 'hover:bg-gray-100 text-gray-700'}`}
                        >
                            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
                            </svg>
                        </button>

                        <div className="flex items-center gap-3">
                            <div className="w-8 h-8 lg:w-10 lg:h-10 rounded-xl bg-gradient-to-br from-blue-500 to-cyan-500 flex items-center justify-center text-white text-lg lg:text-xl font-bold shadow-lg">
                                🏥
                            </div>
                            <div>
                                <h1 className={`text-lg lg:text-xl font-bold bg-gradient-to-r from-blue-600 to-cyan-500 bg-clip-text text-transparent`}>
                                    Cibertronia Salud
                                </h1>
                                <p className={`hidden sm:block text-xs ${isDarkMode ? 'text-gray-400' : 'text-gray-500'}`}>Sistema de Gestión Médica</p>
                            </div>
                        </div>
                    </div>

                    {/* User Menu */}
                    <div className="flex items-center gap-2 lg:gap-4">
                        {/* Theme Toggle */}
                        <button
                            onClick={toggleTheme}
                            className={`p-2 rounded-xl transition-all hover:scale-110 ${isDarkMode ? 'hover:bg-gray-800' : 'hover:bg-gray-100'}`}
                        >
                            {isDarkMode ? '🌙' : '☀️'}
                        </button>

                        {/* Notifications */}
                        <button className={`p-2 rounded-xl transition-all hover:scale-110 relative ${isDarkMode ? 'hover:bg-gray-800' : 'hover:bg-gray-100'}`}>
                            🔔
                            <span className="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full animate-pulse"></span>
                        </button>

                        {/* User Info - Collapsed on Mobile */}
                        <div className={`flex items-center gap-3 px-2 lg:px-4 py-2 rounded-xl ${isDarkMode ? 'bg-gray-800/50 lg:bg-gray-800' : 'bg-gray-100/50 lg:bg-gray-100'}`}>
                            <div className="w-8 h-8 lg:w-10 lg:h-10 rounded-full bg-gradient-to-br from-purple-500 to-pink-500 flex items-center justify-center text-white font-bold text-sm lg:text-base">
                                {user?.nombre ? user.nombre.charAt(0).toUpperCase() : 'U'}
                            </div>
                            <div className="text-left hidden lg:block">
                                <p className={`font-semibold ${isDarkMode ? 'text-white' : 'text-gray-900'}`}>
                                    {user?.nombre ? `${user.nombre} ${user.apellido || ''}`.trim() : 'Usuario'}
                                </p>
                                <p className={`text-xs capitalize ${isDarkMode ? 'text-gray-400' : 'text-gray-500'}`}>
                                    {user?.rol || 'Rol'}
                                </p>
                            </div>
                        </div>

                        {/* Logout - Hidden Text on Mobile */}
                        <button
                            onClick={handleLogout}
                            className={`p-2 lg:px-4 lg:py-2 rounded-xl font-semibold transition-all hover:scale-105 ${isDarkMode ? 'bg-red-600 hover:bg-red-700' : 'bg-red-500 hover:bg-red-600'} text-white shadow-lg flex items-center gap-2`}
                        >
                            <span className="hidden lg:inline">Salir</span>
                            <svg className="w-5 h-5 lg:hidden" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
                            </svg>
                        </button>
                    </div>
                </div>
            </header>

            {/* Mobile Sidebar Overlay */}
            {isMobileMenuOpen && (
                <div
                    className="fixed inset-0 bg-black/50 backdrop-blur-sm z-40 lg:hidden"
                    onClick={() => setIsMobileMenuOpen(false)}
                />
            )}

            {/* Sidebar */}
            <aside
                className={`
                    fixed top-0 left-0 bottom-0 z-50 
                    transition-transform duration-300 ease-in-out
                    ${isMobileMenuOpen ? 'translate-x-0' : '-translate-x-full'}
                    lg:translate-x-0 lg:top-20 
                    w-72
                    ${isDarkMode ? 'bg-gray-900 border-r border-gray-700' : 'bg-white border-r border-gray-200'}
                    shadow-2xl overflow-y-auto
                `}
            >
                {/* Mobile Header in Sidebar */}
                <div className="lg:hidden flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
                    <span className={`font-bold text-lg ${isDarkMode ? 'text-white' : 'text-gray-900'}`}>Menú</span>
                    <button
                        onClick={() => setIsMobileMenuOpen(false)}
                        className={`p-2 rounded-lg ${isDarkMode ? 'hover:bg-gray-800 text-gray-400' : 'hover:bg-gray-100 text-gray-600'}`}
                    >
                        <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>

                <nav className="p-4 space-y-2">
                    {menuItems.map((item) => (
                        <Link
                            key={item.path}
                            to={item.path}
                            onClick={() => setIsMobileMenuOpen(false)}
                            className={`flex items-center gap-3 px-4 py-3 rounded-xl transition-all hover:scale-105 ${isActive(item.path)
                                ? `bg-gradient-to-r ${item.color} text-white shadow-lg`
                                : isDarkMode
                                    ? 'hover:bg-gray-800 text-gray-300'
                                    : 'hover:bg-gray-100 text-gray-700'
                                }`}
                        >
                            <span className="text-2xl">{item.icon}</span>
                            <span className="font-semibold whitespace-nowrap">{item.label}</span>
                        </Link>
                    ))}

                    <div className="my-4 border-t border-gray-200 dark:border-gray-700"></div>

                    {/* Patient Portal Link */}
                    <Link
                        to="/paciente/login"
                        onClick={() => setIsMobileMenuOpen(false)}
                        className={`flex items-center gap-3 px-4 py-3 rounded-xl transition-all hover:scale-105 ${isDarkMode
                            ? 'hover:bg-gray-800 text-gray-300'
                            : 'hover:bg-gray-100 text-gray-700'
                            }`}
                    >
                        <span className="text-2xl">🌐</span>
                        <span className="font-semibold whitespace-nowrap">Portal Paciente</span>
                    </Link>

                    {/* Settings at bottom */}
                    <Link
                        to="/configuracion"
                        onClick={() => setIsMobileMenuOpen(false)}
                        className={`flex items-center gap-3 px-4 py-3 rounded-xl transition-all hover:scale-105 ${isActive('/configuracion')
                            ? 'bg-gradient-to-r from-gray-500 to-slate-600 text-white shadow-lg'
                            : isDarkMode
                                ? 'hover:bg-gray-800 text-gray-300'
                                : 'hover:bg-gray-100 text-gray-700'
                            }`}
                    >
                        <span className="text-2xl">⚙️</span>
                        <span className="font-semibold whitespace-nowrap">Configuración</span>
                    </Link>
                </nav>
            </aside>

            {/* Main Content */}
            <main
                className={`
                    relative z-0
                    pt-20 lg:pt-24
                    px-4 lg:px-8
                    pb-4 lg:pb-8
                    transition-all duration-300 
                    lg:ml-72
                    ml-0
                `}
                style={{ minHeight: 'calc(100vh - 5rem)' }}
            >
                <Outlet />
            </main>
        </div>
    );
}
