import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { useQuery } from '@tanstack/react-query';
import { organizations } from '../services/api';
import { useState, useEffect } from 'react';
import { cn } from '../lib/utils';
import {
    LayoutDashboard, TicketCheck, Plug, Users, BarChart3, Settings,
    ChevronDown, ChevronRight, Search, Bell, PanelLeftClose, PanelLeftOpen,
    LogOut, Building2, Plus, Zap, Shield, ChevronsUpDown, Command
} from 'lucide-react';

const navSections = [
    {
        label: 'Main',
        items: [
            { path: '/', label: 'Dashboard', icon: LayoutDashboard },
            { path: '/issues', label: 'Issues', icon: TicketCheck },
        ]
    },
    {
        label: 'Management',
        items: [
            { path: '/integrations', label: 'Integrations', icon: Plug },
            { path: '/team', label: 'Team', icon: Users },
            { path: '/reports', label: 'Reports', icon: BarChart3 },
        ]
    },
    {
        label: 'System',
        items: [
            { path: '/settings', label: 'Settings', icon: Settings },
        ]
    }
];

const breadcrumbMap = {
    '/': 'Dashboard',
    '/issues': 'Issues',
    '/integrations': 'Integrations',
    '/team': 'Team',
    '/reports': 'Reports',
    '/settings': 'Settings',
};

export default function Layout() {
    const { user, logout, currentOrg, selectOrg } = useAuth();
    const location = useLocation();
    const navigate = useNavigate();
    const [collapsed, setCollapsed] = useState(false);
    const [showOrgMenu, setShowOrgMenu] = useState(false);
    const [showSearch, setShowSearch] = useState(false);
    const [showNotifs, setShowNotifs] = useState(false);
    const [searchQuery, setSearchQuery] = useState('');

    const { data: orgs } = useQuery({
        queryKey: ['organizations'],
        queryFn: () => organizations.list()
    });

    // Cmd+K shortcut
    useEffect(() => {
        const handler = (e) => {
            if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
                e.preventDefault();
                setShowSearch(s => !s);
            }
            if (e.key === 'Escape') {
                setShowSearch(false);
                setShowOrgMenu(false);
            }
        };
        window.addEventListener('keydown', handler);
        return () => window.removeEventListener('keydown', handler);
    }, []);

    const getBreadcrumbs = () => {
        const parts = location.pathname.split('/').filter(Boolean);
        if (parts.length === 0) return [{ label: 'Dashboard', path: '/' }];
        
        const crumbs = [];
        let current = '';
        for (const part of parts) {
            current += `/${part}`;
            crumbs.push({
                label: breadcrumbMap[current] || part.charAt(0).toUpperCase() + part.slice(1),
                path: current
            });
        }
        return crumbs;
    };

    const isActive = (path) => {
        if (path === '/') return location.pathname === '/';
        return location.pathname.startsWith(path);
    };

    return (
        <div className="min-h-screen flex bg-gray-950 text-gray-200">
            {/* Search Modal */}
            {showSearch && (
                <div className="fixed inset-0 z-50 flex items-start justify-center pt-[20vh]" onClick={() => setShowSearch(false)}>
                    <div className="absolute inset-0 bg-black/60 backdrop-blur-sm" />
                    <div className="relative w-full max-w-lg mx-4 animate-slide-up" onClick={e => e.stopPropagation()}>
                        <div className="card border-gray-700 shadow-2xl">
                            <div className="flex items-center gap-3 px-4 py-3 border-b border-gray-800">
                                <Search size={18} className="text-gray-500" />
                                <input
                                    autoFocus
                                    value={searchQuery}
                                    onChange={e => setSearchQuery(e.target.value)}
                                    placeholder="Search issues, projects, settings..."
                                    className="flex-1 bg-transparent text-sm outline-none placeholder:text-gray-500"
                                />
                                <kbd className="kbd">ESC</kbd>
                            </div>
                            <div className="p-2 max-h-80 overflow-auto">
                                {['Dashboard', 'Issues', 'Integrations', 'Team', 'Reports', 'Settings']
                                    .filter(item => item.toLowerCase().includes(searchQuery.toLowerCase()))
                                    .map(item => (
                                        <button
                                            key={item}
                                            className="w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm text-gray-300 hover:bg-gray-800 transition-colors"
                                            onClick={() => {
                                                navigate(`/${item.toLowerCase() === 'dashboard' ? '' : item.toLowerCase()}`);
                                                setShowSearch(false);
                                                setSearchQuery('');
                                            }}
                                        >
                                            <ChevronRight size={14} className="text-gray-600" />
                                            {item}
                                        </button>
                                    ))
                                }
                                {searchQuery && (
                                    <div className="px-3 py-6 text-center text-sm text-gray-500">
                                        Press Enter to search for "{searchQuery}"
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* Sidebar */}
            <aside className={cn(
                "fixed top-0 left-0 h-full flex flex-col border-r border-gray-800/50 bg-gray-950 z-40 transition-all duration-300",
                collapsed ? "w-[68px]" : "w-[260px]"
            )}>
                {/* Logo */}
                <div className={cn("h-14 flex items-center border-b border-gray-800/50 px-4", collapsed && "justify-center px-0")}>
                    {collapsed ? (
                        <div className="w-8 h-8 rounded-lg bg-indigo-600 flex items-center justify-center">
                            <Zap size={16} className="text-white" />
                        </div>
                    ) : (
                        <div className="flex items-center gap-2.5">
                            <div className="w-8 h-8 rounded-lg bg-indigo-600 flex items-center justify-center shadow-lg shadow-indigo-500/20">
                                <Zap size={16} className="text-white" />
                            </div>
                            <div>
                                <h1 className="text-sm font-semibold text-white">JIRA AI Fixer</h1>
                                <p className="text-[10px] text-gray-500 font-medium">Enterprise v2.0</p>
                            </div>
                        </div>
                    )}
                </div>

                {/* Org selector */}
                {!collapsed && (
                    <div className="px-3 py-3 border-b border-gray-800/50 relative">
                        <button
                            onClick={() => setShowOrgMenu(!showOrgMenu)}
                            className="w-full flex items-center gap-2.5 px-3 py-2 rounded-lg bg-gray-900/60 hover:bg-gray-800/80 border border-gray-800/50 transition-all"
                        >
                            <div className="w-6 h-6 rounded bg-indigo-600/20 flex items-center justify-center flex-shrink-0">
                                <Building2 size={12} className="text-indigo-400" />
                            </div>
                            <span className="flex-1 text-left text-sm truncate">{currentOrg?.name || 'Select org'}</span>
                            <ChevronsUpDown size={14} className="text-gray-500" />
                        </button>
                        {showOrgMenu && orgs?.data && (
                            <div className="absolute left-3 right-3 top-full mt-1 bg-gray-900 border border-gray-700 rounded-lg shadow-xl z-50 animate-slide-up">
                                {orgs.data.map(org => (
                                    <button
                                        key={org.id}
                                        onClick={() => { selectOrg(org); setShowOrgMenu(false); }}
                                        className={cn(
                                            "w-full flex items-center gap-2.5 px-3 py-2 text-sm hover:bg-gray-800 first:rounded-t-lg last:rounded-b-lg transition-colors",
                                            currentOrg?.id === org.id && "bg-indigo-600/10 text-indigo-400"
                                        )}
                                    >
                                        <Building2 size={14} />
                                        {org.name}
                                    </button>
                                ))}
                                <button
                                    onClick={() => { navigate('/settings'); setShowOrgMenu(false); }}
                                    className="w-full flex items-center gap-2.5 px-3 py-2 text-sm text-indigo-400 hover:bg-gray-800 border-t border-gray-800 rounded-b-lg"
                                >
                                    <Plus size={14} />
                                    New organization
                                </button>
                            </div>
                        )}
                    </div>
                )}

                {/* Search trigger */}
                {!collapsed && (
                    <div className="px-3 pt-3">
                        <button
                            onClick={() => setShowSearch(true)}
                            className="w-full flex items-center gap-2.5 px-3 py-2 rounded-lg text-gray-500 hover:text-gray-300 bg-gray-900/40 hover:bg-gray-800/60 border border-gray-800/30 transition-all text-sm"
                        >
                            <Search size={14} />
                            <span className="flex-1 text-left">Search...</span>
                            <div className="flex items-center gap-0.5">
                                <kbd className="kbd">⌘</kbd>
                                <kbd className="kbd">K</kbd>
                            </div>
                        </button>
                    </div>
                )}

                {/* Navigation */}
                <nav className="flex-1 overflow-auto px-3 py-4 space-y-5">
                    {navSections.map(section => (
                        <div key={section.label}>
                            {!collapsed && (
                                <p className="text-[10px] font-semibold uppercase tracking-wider text-gray-600 px-3 mb-1.5">
                                    {section.label}
                                </p>
                            )}
                            <div className="space-y-0.5">
                                {section.items.map(item => {
                                    const Icon = item.icon;
                                    const active = isActive(item.path);
                                    return (
                                        <Link
                                            key={item.path}
                                            to={item.path}
                                            title={collapsed ? item.label : undefined}
                                            className={cn(
                                                "sidebar-item",
                                                active ? "sidebar-item-active" : "sidebar-item-inactive",
                                                collapsed && "justify-center px-0"
                                            )}
                                        >
                                            <Icon size={18} strokeWidth={active ? 2 : 1.5} />
                                            {!collapsed && <span>{item.label}</span>}
                                        </Link>
                                    );
                                })}
                            </div>
                        </div>
                    ))}
                </nav>

                {/* Collapse toggle */}
                <div className="px-3 py-2 border-t border-gray-800/50">
                    <button
                        onClick={() => setCollapsed(!collapsed)}
                        className={cn("sidebar-item sidebar-item-inactive w-full", collapsed && "justify-center px-0")}
                    >
                        {collapsed ? <PanelLeftOpen size={18} /> : <PanelLeftClose size={18} />}
                        {!collapsed && <span>Collapse</span>}
                    </button>
                </div>

                {/* User */}
                <div className={cn("px-3 py-3 border-t border-gray-800/50", collapsed && "px-2")}>
                    <div className={cn("flex items-center gap-2.5", collapsed && "justify-center")}>
                        <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center text-xs font-semibold text-white flex-shrink-0">
                            {user?.full_name?.[0]?.toUpperCase() || user?.email?.[0]?.toUpperCase() || '?'}
                        </div>
                        {!collapsed && (
                            <div className="flex-1 min-w-0">
                                <p className="text-sm font-medium truncate">{user?.full_name || user?.email}</p>
                                <button onClick={logout} className="text-xs text-gray-500 hover:text-red-400 transition-colors flex items-center gap-1">
                                    <LogOut size={10} />
                                    Sign out
                                </button>
                            </div>
                        )}
                    </div>
                </div>
            </aside>

            {/* Main area */}
            <div className={cn("flex-1 flex flex-col transition-all duration-300", collapsed ? "ml-[68px]" : "ml-[260px]")}>
                {/* Top header */}
                <header className="h-14 flex items-center justify-between px-6 border-b border-gray-800/50 bg-gray-950/80 backdrop-blur-md sticky top-0 z-30">
                    {/* Breadcrumbs */}
                    <div className="flex items-center gap-1.5 text-sm">
                        {getBreadcrumbs().map((crumb, i) => (
                            <div key={crumb.path} className="flex items-center gap-1.5">
                                {i > 0 && <ChevronRight size={12} className="text-gray-600" />}
                                <Link
                                    to={crumb.path}
                                    className={cn(
                                        "hover:text-white transition-colors",
                                        i === getBreadcrumbs().length - 1 ? "text-white font-medium" : "text-gray-400"
                                    )}
                                >
                                    {crumb.label}
                                </Link>
                            </div>
                        ))}
                    </div>

                    {/* Header actions */}
                    <div className="flex items-center gap-2">
                        <button
                            onClick={() => setShowSearch(true)}
                            className="btn-ghost btn-icon rounded-lg"
                        >
                            <Search size={16} />
                        </button>
                        <button
                            onClick={() => setShowNotifs(!showNotifs)}
                            className="btn-ghost btn-icon rounded-lg relative"
                        >
                            <Bell size={16} />
                            <span className="absolute top-1.5 right-1.5 w-2 h-2 rounded-full bg-indigo-500" />
                        </button>
                    </div>
                </header>

                {/* Page content */}
                <main className="flex-1 overflow-auto">
                    <Outlet />
                </main>
            </div>
        </div>
    );
}
