import { A, useLocation } from "@solidjs/router";
import {
  Bell,
  Building2,
  Calendar,
  CalendarDays,
  Inbox,
  LayoutGrid,
  LayoutList,
  Link,
  LogOut,
  Mail,
  Moon,
  NotebookText,
  Search,
  Settings,
  Sun,
  TimerReset,
  Users,
  Wifi,
  WifiOff
} from "lucide-solid";
import { For, Show, type JSX } from "solid-js";

import { useApp } from "~/lib/app-context";
import { CommandPalette } from "./command-palette";
import { GlobalSearch } from "./global-search";
import { NotificationsDropdown } from "./notifications-dropdown";

const navItems = [
  { href: "today", label: "Today", icon: LayoutGrid },
  { href: "inbox", label: "Inbox", icon: Inbox },
  { href: "calendar", label: "Calendar", icon: CalendarDays },
  { href: "board", label: "Board", icon: Bell },
  { href: "list", label: "List", icon: LayoutList },
  { href: "timeline", label: "Timeline", icon: Calendar },
  { href: "mail", label: "Mail", icon: Mail },
  { href: "notes", label: "Notes", icon: NotebookText },
  { href: "contacts", label: "Contacts", icon: Users },
  { href: "companies", label: "Companies", icon: Building2 },
  { href: "focus", label: "Focus", icon: TimerReset },
  { href: "integrations", label: "Integrations", icon: Link },
  { href: "settings", label: "Settings", icon: Settings }
];

export default function AppShell(props: { children: JSX.Element }) {
  const app = useApp();
  const location = useLocation();
  const workspaceSlug = () => location.pathname.split("/")[2] || app.primaryWorkspace()?.slug || "personal";
  const workspace = () => app.workspaceForSlug(workspaceSlug()) ?? app.primaryWorkspace();
  const pendingSyncCount = () => app.state.offlineQueue.filter(item => item.status !== "synced").length;

  return (
    <>
      <CommandPalette />
      <GlobalSearch />
      <div class="min-h-screen flex" style="position: relative; z-index: 1;">
      {/* Desktop Sidebar */}
      <aside class="hidden w-72 shrink-0 border-r border-[var(--border)] bg-[var(--surface)] lg:flex lg:flex-col relative">
        {/* Decorative accent line */}
        <div class="absolute top-0 left-0 w-1 h-full bg-gradient-to-b from-[var(--accent)] via-[var(--secondary)] to-transparent opacity-60" />
        
        {/* Logo */}
        <div class="border-b border-[var(--border)] px-7 py-6 relative">
          <div class="flex items-center gap-3">
            <div class="flex h-11 w-11 items-center justify-center rounded-2xl bg-gradient-to-br from-[var(--accent)] via-[var(--accent-hover)] to-[var(--secondary)] text-white text-base font-bold shadow-lg relative overflow-hidden">
              <div class="absolute inset-0 bg-gradient-to-tr from-transparent via-white/20 to-transparent" />
              <span class="relative">P</span>
            </div>
            <div>
              <span class="text-xl font-semibold tracking-tight block" style="font-family: var(--font-serif); font-variation-settings: 'opsz' 144;">Productier</span>
              <span class="text-[10px] font-medium tracking-wider uppercase text-[var(--text-muted)] block mt-0.5">Workspace</span>
            </div>
          </div>
        </div>

        {/* Workspace selector */}
        <div class="border-b border-[var(--border)] px-6 py-5">
          <div class="group flex items-center gap-3 rounded-2xl bg-gradient-to-br from-[var(--bg-subtle)] to-[var(--bg-muted)] px-5 py-4 transition-all duration-300 hover:shadow-md hover:scale-[1.02] cursor-pointer relative overflow-hidden">
            <div class="absolute inset-0 bg-gradient-to-br from-[var(--accent)]/5 to-[var(--secondary)]/5 opacity-0 group-hover:opacity-100 transition-opacity duration-300" />
            <div class="flex h-12 w-12 items-center justify-center rounded-xl bg-gradient-to-br from-[var(--accent-subtle)] via-[var(--accent-muted)] to-[var(--secondary-subtle)] text-[var(--accent)] text-base font-bold shadow-sm relative z-10">
              {workspace()?.name?.charAt(0) ?? "P"}
            </div>
            <div class="min-w-0 flex-1 relative z-10">
              <p class="truncate text-sm font-semibold">{workspace()?.name}</p>
              <p class="text-xs text-[var(--text-muted)] capitalize flex items-center gap-1.5 mt-0.5">
                <span class="inline-block w-1.5 h-1.5 rounded-full bg-[var(--success)]" />
                {workspace()?.role}
              </p>
            </div>
          </div>
        </div>

        {/* Navigation */}
        <nav class="flex-1 overflow-y-auto scrollbar-thin p-5">
          <div class="space-y-2">
            <For each={navItems}>
              {item => {
                const Icon = item.icon;
                const href = () => `/app/${workspaceSlug()}/${item.href}`;
                const active = () => location.pathname === href();
                return (
                  <A
                    href={href()}
                    class="group flex items-center gap-3.5 rounded-xl px-4 py-3.5 text-sm font-medium transition-all duration-200 relative overflow-hidden"
                    classList={{
                      "bg-gradient-to-r from-[var(--accent)] to-[var(--accent-hover)] text-white shadow-lg shadow-[var(--accent)]/20": active(),
                      "text-[var(--text-muted)] hover:text-[var(--text)] hover:bg-[var(--bg-subtle)]": !active()
                    }}
                  >
                    <Show when={active()}>
                      <div class="absolute inset-0 bg-gradient-to-r from-white/10 to-transparent opacity-50" />
                    </Show>
                    <Icon size={20} class="relative z-10 transition-transform duration-200 group-hover:scale-110" />
                    <span class="relative z-10">{item.label}</span>
                    <Show when={active()}>
                      <div class="absolute right-0 top-1/2 -translate-y-1/2 w-1 h-8 bg-white/40 rounded-l-full" />
                    </Show>
                  </A>
                );
              }}
            </For>
          </div>
        </nav>

        {/* Sync status */}
        <div class="border-t border-[var(--border)] px-6 py-4 bg-[var(--bg-subtle)]">
          <div class="flex items-center gap-3 text-xs">
            <Show when={app.online()} fallback={
              <div class="flex items-center gap-2.5 px-3 py-2 rounded-lg bg-[var(--error-muted)] text-[var(--error)] w-full">
                <WifiOff size={16} />
                <span class="font-medium">Offline mode</span>
              </div>
            }>
              <div class="flex items-center gap-2.5 px-3 py-2 rounded-lg w-full transition-colors duration-200"
                classList={{
                  "bg-[var(--warning-muted)] text-[var(--warning)]": pendingSyncCount() > 0,
                  "bg-[var(--success-muted)] text-[var(--success)]": pendingSyncCount() === 0
                }}
              >
                <div class={`status-dot ${pendingSyncCount() > 0 ? 'syncing' : 'online'}`} />
                <span class="font-medium">
                  {pendingSyncCount() > 0 ? `Syncing ${pendingSyncCount()}` : "All synced"}
                </span>
              </div>
            </Show>
          </div>
        </div>

        {/* User section */}
        <div class="border-t border-[var(--border)] px-6 py-5">
          <div class="flex items-center justify-between gap-3">
            <div class="min-w-0 flex-1">
              <p class="truncate text-sm font-semibold">{app.state.session?.name}</p>
              <p class="truncate text-xs text-[var(--text-muted)] mt-0.5">{app.state.session?.email}</p>
            </div>
            <button
              class="group flex h-10 w-10 items-center justify-center rounded-xl text-[var(--text-muted)] transition-all duration-200 hover:bg-[var(--error-muted)] hover:text-[var(--error)] hover:shadow-md hover:scale-105"
              onClick={() => void app.logout()}
              aria-label="Sign out"
            >
              <LogOut size={18} class="transition-transform duration-200 group-hover:translate-x-0.5" />
            </button>
          </div>
        </div>
      </aside>

      {/* Main content area */}
      <div class="flex min-w-0 flex-1 flex-col">
        {/* Header */}
        <header class="sticky top-0 z-30 border-b border-[var(--border)] glass backdrop-blur-xl">
          <div class="flex h-16 items-center justify-between px-6 lg:px-8">
            {/* Left: Page context */}
            <div class="flex items-center gap-4">
              <div class="hidden lg:block">
                <h1 class="text-lg font-semibold tracking-tight" style="font-family: var(--font-serif); font-variation-settings: 'opsz' 120;">{workspace()?.name}</h1>
              </div>
              <div class="lg:hidden flex items-center gap-3">
                <div class="flex h-9 w-9 items-center justify-center rounded-xl bg-gradient-to-br from-[var(--accent)] to-[var(--secondary)] text-white text-sm font-bold shadow-md">
                  P
                </div>
                <span class="text-base font-semibold" style="font-family: var(--font-serif); font-variation-settings: 'opsz' 120;">Productier</span>
              </div>
            </div>

            {/* Right: Actions */}
            <div class="flex items-center gap-3">
              <NotificationsDropdown />
              <button
                class="group flex items-center gap-2 px-3 py-1.5 rounded-lg border border-[var(--border)] bg-[var(--surface)] text-[var(--text-muted)] text-sm hover:bg-[var(--surface-hover)] transition-colors"
                onClick={() => {
                  const event = new KeyboardEvent("keydown", { key: "/", metaKey: true });
                  window.dispatchEvent(event);
                }}
              >
                <Search size={16} />
                <span class="hidden sm:inline">Search</span>
                <kbd class="hidden sm:inline px-1.5 py-0.5 rounded bg-[var(--bg-subtle)] text-xs">⌘/</kbd>
              </button>
              <Show when={pendingSyncCount() > 0}>
                <span class="hidden rounded-full bg-[var(--warning-muted)] px-3.5 py-2 text-xs font-semibold text-[var(--warning)] sm:inline-flex items-center gap-2 shadow-sm">
                  <div class="status-dot syncing" />
                  {pendingSyncCount()} pending
                </span>
              </Show>
              <button
                class="group flex h-11 w-11 items-center justify-center rounded-xl text-[var(--text-muted)] transition-all duration-200 hover:bg-[var(--bg-subtle)] hover:text-[var(--text)] hover:shadow-md hover:scale-105"
                onClick={() => app.setTheme(app.state.theme === "dark" ? "light" : "dark")}
                aria-label="Toggle theme"
              >
                <Show when={app.state.theme === "dark"} fallback={<Moon size={19} class="transition-transform duration-200 group-hover:rotate-12" />}>
                  <Sun size={19} class="transition-transform duration-200 group-hover:rotate-45" />
                </Show>
              </button>
            </div>
          </div>
        </header>

        {/* Main content */}
        <main class="flex-1 overflow-y-auto scrollbar-thin p-6 lg:p-10">
          <div class="mx-auto max-w-7xl">
            {props.children}
          </div>
        </main>

        {/* Mobile bottom navigation */}
        <nav class="fixed inset-x-0 bottom-0 z-40 border-t border-[var(--border)] glass backdrop-blur-xl lg:hidden">
          <div class="flex h-20 items-center justify-around px-2">
            <For each={navItems.slice(0, 5)}>
              {item => {
                const Icon = item.icon;
                const href = `/app/${workspaceSlug()}/${item.href}`;
                const active = () => location.pathname === href;
                return (
                  <A
                    href={href}
                    class="group flex flex-col items-center gap-1.5 rounded-xl px-5 py-2.5 transition-all duration-200"
                    classList={{
                      "text-[var(--accent)]": active(),
                      "text-[var(--text-muted)]": !active()
                    }}
                  >
                    <div class="relative">
                      <Icon size={22} class="transition-transform duration-200 group-active:scale-90" />
                      <Show when={active()}>
                        <div class="absolute -bottom-1 left-1/2 -translate-x-1/2 w-1 h-1 rounded-full bg-[var(--accent)]" />
                      </Show>
                    </div>
                    <span class="text-[10px] font-semibold tracking-wide">{item.label}</span>
                  </A>
                );
              }}
            </For>
          </div>
        </nav>
      </div>
    </div>
    </>
  );
}
