"use client";

import { useState, useEffect, useCallback, type ReactNode } from "react";
import { useRouter, usePathname } from "next/navigation";
import type { SessionPayload } from "@/lib/auth";
import {
  Home, Search, Bell, Settings, Menu, X, Command, Users, BarChart3,
  MessageSquare, Shield, GraduationCap, ChevronDown, ChevronRight,
  Activity, Stethoscope, Brain, HeartPulse, Monitor, Bed, LayoutDashboard,
  Bot, Siren, TrendingUp, FileText, Pill, FlaskConical, Smartphone,
} from "lucide-react";

interface Props { session: SessionPayload; children: ReactNode; }

const navSections = [
  {
    title: "WORKSPACE",
    items: [
      { href: "/dashboard", icon: Home, label: "Command Center" },
      { href: "/dashboard/patients", icon: Users, label: "Patient Panel" },
      { href: "/dashboard/messages", icon: MessageSquare, label: "Inbox" },
    ],
  },
  {
    title: "SPECIALTY",
    items: [
      { href: "/dashboard/ed-board", icon: Siren, label: "ED Tracking Board" },
      { href: "/dashboard/inpatient", icon: Bed, label: "Inpatient Census" },
      { href: "/dashboard/telehealth", icon: Monitor, label: "Telehealth" },
    ],
  },
  {
    title: "INTELLIGENCE",
    items: [
      { href: "/dashboard/population", icon: TrendingUp, label: "Population Health" },
      { href: "/dashboard/analytics", icon: BarChart3, label: "Analytics" },
      { href: "/dashboard/ai-center", icon: Bot, label: "AI Command" },
    ],
  },
  {
    title: "ADMIN",
    items: [
      { href: "/dashboard/quality", icon: Shield, label: "Quality & Safety" },
      { href: "/dashboard/academy", icon: GraduationCap, label: "Academy" },
      { href: "/dashboard/settings", icon: Settings, label: "Settings" },
    ],
  },
];

export function DashboardShell({ session, children }: Props) {
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const [showSearch, setShowSearch] = useState(false);
  const [showUserMenu, setShowUserMenu] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const router = useRouter();
  const pathname = usePathname();
  const initials = `${session.firstName[0]}${session.lastName[0]}`;

  // Keyboard shortcuts — ⌘K / Ctrl+K for command palette
  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key === "k") {
        e.preventDefault();
        setShowSearch((p) => !p);
      }
      if (e.key === "Escape") { setShowSearch(false); setShowUserMenu(false); }
    };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, []);

  const allCommands = [
    { label: "Mary Njeri", sub: "MRN: KNH-447182 • Diabetes F/U", href: "/dashboard/patient/1", cat: "patients" },
    { label: "John Kamau", sub: "MRN: KNH-552930 • HTN Review", href: "/dashboard/patient/2", cat: "patients" },
    { label: "Fatuma Hassan", sub: "MRN: KNH-663871 • Anxiety F/U", href: "/dashboard/patient/3", cat: "patients" },
    { label: "David Otieno", sub: "MRN: KNH-774102 • Back Pain", href: "/dashboard/patient/4", cat: "patients" },
    { label: "Agnes Wambui", sub: "MRN: KNH-885419 • Annual Wellness", href: "/dashboard/patient/5", cat: "patients" },
    { label: "Joseph Mwangi", sub: "MRN: KNH-996738 • CHF Monitoring", href: "/dashboard/patient/6", cat: "patients" },
    ...navSections.flatMap((s) => s.items.map((i) => ({ label: i.label, sub: `Navigate to ${i.label}`, href: i.href, cat: "navigation" }))),
    { label: "New Order", sub: "Create a new order for a patient", href: "/dashboard", cat: "actions" },
    { label: "Write Note", sub: "Start a new clinical note", href: "/dashboard", cat: "actions" },
    { label: "Refill Queue", sub: "View pending medication refills", href: "/dashboard", cat: "actions" },
  ];

  const filteredCommands = searchQuery.length > 0
    ? allCommands.filter((c) => `${c.label} ${c.sub}`.toLowerCase().includes(searchQuery.toLowerCase()))
    : allCommands.slice(0, 8);

  return (
    <div className="h-screen flex flex-col overflow-hidden bg-slate-50">
      {/* ── Top Navigation Bar ── */}
      <header className="h-13 bg-white border-b border-slate-200 flex items-center px-4 gap-3 shrink-0 z-50">
        <button onClick={() => setSidebarCollapsed(!sidebarCollapsed)} className="p-2 hover:bg-slate-100 rounded-lg transition-colors text-slate-500">
          {sidebarCollapsed ? <Menu size={18} /> : <X size={18} />}
        </button>

        <div className="flex items-center gap-2 cursor-pointer" onClick={() => router.push("/dashboard")}>
          <div className="w-7 h-7 rounded-lg bg-clinical-600 flex items-center justify-center shrink-0">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M12 2L2 7L12 12L22 7L12 2Z" fill="white"/><path d="M2 17L12 22L22 17" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/><path d="M2 12L12 17L22 12" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </div>
          <span className="font-bold text-slate-800 text-sm hidden sm:block">Clevora <span className="text-clinical-600">Clinical</span></span>
        </div>

        <div className="flex-1 max-w-xl mx-4">
          <button onClick={() => setShowSearch(true)} className="w-full flex items-center gap-2 px-3 py-2 bg-slate-50 border border-slate-200 rounded-xl text-sm text-slate-400 hover:border-clinical-300 transition-colors">
            <Search size={15} />
            <span className="flex-1 text-left">Search patients, orders, actions…</span>
            <kbd className="hidden sm:flex items-center gap-1 px-1.5 py-0.5 bg-white border border-slate-200 rounded text-[10px] font-medium text-slate-400"><Command size={10} />K</kbd>
          </button>
        </div>

        <div className="flex items-center gap-1">
          <button className="relative p-2 hover:bg-slate-100 rounded-lg transition-colors text-slate-500">
            <Bell size={18} /><span className="absolute top-1.5 right-1.5 w-2 h-2 bg-red-500 rounded-full" />
          </button>
          <button onClick={() => router.push("/dashboard/settings")} className="p-2 hover:bg-slate-100 rounded-lg transition-colors text-slate-500">
            <Settings size={18} />
          </button>
          <div className="relative">
            <button onClick={() => setShowUserMenu(!showUserMenu)} className="flex items-center gap-2 px-2 py-1.5 hover:bg-slate-100 rounded-xl transition-colors">
              <div className="w-8 h-8 rounded-full bg-clinical-600 text-white flex items-center justify-center text-xs font-semibold">{initials}</div>
              <div className="hidden md:block text-left">
                <p className="text-xs font-semibold text-slate-800">Dr. {session.firstName} {session.lastName}</p>
                <p className="text-[10px] text-slate-400">{session.specialty}</p>
              </div>
              <ChevronDown size={14} className="text-slate-400 hidden md:block" />
            </button>
            {showUserMenu && (
              <>
                <div className="fixed inset-0 z-40" onClick={() => setShowUserMenu(false)} />
                <div className="absolute right-0 top-full mt-1 w-64 bg-white border border-slate-200 rounded-xl shadow-lg z-50 py-1">
                  <div className="px-4 py-3 border-b border-slate-100">
                    <p className="text-sm font-semibold text-slate-800">Dr. {session.firstName} {session.lastName}</p>
                    <p className="text-xs text-slate-500">{session.email}</p>
                    <p className="text-xs text-slate-400 mt-0.5">{session.specialty} • Reg: KE-MED-2024-001</p>
                  </div>
                  <button onClick={() => { setShowUserMenu(false); router.push("/dashboard/settings"); }} className="w-full flex items-center gap-2 px-4 py-2.5 text-sm text-slate-700 hover:bg-slate-50"><Settings size={14} />Settings & Preferences</button>
                  <button onClick={() => { setShowUserMenu(false); router.push("/dashboard/academy"); }} className="w-full flex items-center gap-2 px-4 py-2.5 text-sm text-slate-700 hover:bg-slate-50"><GraduationCap size={14} />Clevora Academy</button>
                </div>
              </>
            )}
          </div>
        </div>
      </header>

      <div className="flex flex-1 overflow-hidden">
        {/* ── Left Sidebar ── */}
        <nav className={`${sidebarCollapsed ? "w-14" : "w-52"} bg-white border-r border-slate-200 flex flex-col shrink-0 transition-all duration-300 overflow-y-auto overflow-x-hidden`}>
          <div className="flex-1 py-2 px-1.5 space-y-3">
            {navSections.map((section) => (
              <div key={section.title}>
                {!sidebarCollapsed && <p className="px-2.5 pt-2 pb-1 text-[9px] font-bold text-slate-400 tracking-wider">{section.title}</p>}
                {section.items.map((item) => {
                  const isActive = item.href === "/dashboard" ? pathname === "/dashboard" : pathname.startsWith(item.href);
                  return (
                    <button key={item.href} onClick={() => router.push(item.href)} title={sidebarCollapsed ? item.label : undefined}
                      className={`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-[13px] font-medium transition-all ${isActive ? "bg-clinical-50 text-clinical-700" : "text-slate-500 hover:bg-slate-50 hover:text-slate-700"}`}>
                      <item.icon size={16} className="shrink-0" />
                      {!sidebarCollapsed && <span className="truncate">{item.label}</span>}
                    </button>
                  );
                })}
              </div>
            ))}
          </div>
          {!sidebarCollapsed && (
            <div className="p-2 border-t border-slate-100">
              <div className="bg-gradient-to-br from-clinical-50 to-accent-teal-light rounded-xl p-2.5">
                <div className="flex items-center gap-2 mb-0.5"><span className="text-base">🤖</span><span className="text-[10px] font-semibold text-clinical-800">AI Agents Active</span></div>
                <p className="text-[9px] text-clinical-600">5 agents • 2 need review</p>
              </div>
            </div>
          )}
        </nav>

        <main className="flex-1 overflow-auto">{children}</main>
      </div>

      {/* ── Command Palette ── */}
      {showSearch && (
        <>
          <div className="fixed inset-0 bg-black/40 z-50" onClick={() => { setShowSearch(false); setSearchQuery(""); }} />
          <div className="fixed top-[12%] left-1/2 -translate-x-1/2 w-full max-w-2xl bg-white rounded-2xl shadow-2xl z-50 overflow-hidden">
            <div className="flex items-center gap-3 px-5 py-4 border-b border-slate-100">
              <Search size={18} className="text-slate-400" />
              <input autoFocus value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} placeholder="Search patients, actions, features…" className="flex-1 text-sm outline-none placeholder:text-slate-400" />
              <kbd className="px-2 py-1 bg-slate-100 rounded text-xs text-slate-400">ESC</kbd>
            </div>
            <div className="p-2 max-h-96 overflow-auto">
              {["patients", "navigation", "actions"].map((cat) => {
                const items = filteredCommands.filter((c) => c.cat === cat);
                if (items.length === 0) return null;
                return (
                  <div key={cat}>
                    <p className="text-[9px] font-bold text-slate-400 px-3 pt-2 pb-1 uppercase tracking-wider">{cat}</p>
                    {items.map((c) => (
                      <button key={c.label + c.href} onClick={() => { setShowSearch(false); setSearchQuery(""); router.push(c.href); }}
                        className="w-full flex items-center gap-3 px-3 py-2.5 hover:bg-clinical-50 rounded-lg text-left transition-colors">
                        <div className="w-8 h-8 rounded-full bg-clinical-100 text-clinical-600 flex items-center justify-center text-[10px] font-bold shrink-0">
                          {cat === "patients" ? c.label.split(" ").map((n) => n[0]).join("") : cat === "navigation" ? "→" : "⚡"}
                        </div>
                        <div className="flex-1 min-w-0"><p className="text-sm font-medium text-slate-800">{c.label}</p><p className="text-xs text-slate-400 truncate">{c.sub}</p></div>
                        <ChevronRight size={14} className="text-slate-300" />
                      </button>
                    ))}
                  </div>
                );
              })}
            </div>
          </div>
        </>
      )}
    </div>
  );
}
