"use client";

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import {
  Bell,
  Boxes,
  ChartNoAxesCombined,
  ChevronDown,
  CircleDollarSign,
  LayoutDashboard,
  Leaf,
  Search,
  Settings,
  Store,
  Users,
} from "lucide-react";
import { useState, type ReactNode } from "react";
import { cn } from "@/lib/utils";

const navigation = [
  { href: "/", label: "Overview", icon: LayoutDashboard },
  { href: "/inventory", label: "Inventory", icon: Boxes },
  { href: "/branches", label: "Branches", icon: Store },
  { href: "/sales-team", label: "Sales team", icon: Users },
  { href: "/recommendations", label: "Recommendations", icon: CircleDollarSign },
  { href: "/alerts", label: "Alerts", icon: Bell },
];

interface SearchItem {
  id: string;
  label: string;
  detail: string;
  href: string;
  keywords: string;
  type: string;
}

export function DashboardShell({
  children,
  searchItems,
}: {
  children: ReactNode;
  searchItems: SearchItem[];
}) {
  const pathname = usePathname();
  const router = useRouter();
  const [query, setQuery] = useState("");
  const [profileOpen, setProfileOpen] = useState(false);
  const matches = query.trim().length
    ? searchItems
        .filter((item) => item.keywords.toLowerCase().includes(query.trim().toLowerCase()))
        .slice(0, 7)
    : [];

  if (pathname === "/login") {
    return <>{children}</>;
  }

  return (
    <div className="min-h-screen bg-[var(--surface)] text-slate-950">
      <aside className="fixed inset-y-0 left-0 z-40 hidden w-64 flex-col border-r border-slate-200/80 bg-white px-4 py-5 lg:flex">
        <Link href="/" className="flex items-center gap-3 px-3">
          <span className="grid size-10 place-items-center rounded-xl bg-emerald-600 text-white shadow-sm shadow-emerald-200">
            <Leaf className="size-5" />
          </span>
          <span>
            <span className="block text-lg font-bold tracking-tight">Solaire</span>
            <span className="block text-[11px] font-medium text-slate-400">Inventory intelligence</span>
          </span>
        </Link>

        <nav className="mt-9 space-y-1">
          <p className="mb-2 px-3 text-[10px] font-bold uppercase tracking-[0.18em] text-slate-400">
            Workspace
          </p>
          {navigation.map((item) => {
            const active = item.href === "/" ? pathname === "/" : pathname.startsWith(item.href);
            return (
              <Link
                key={item.href}
                href={item.href}
                className={cn(
                  "flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium transition",
                  active
                    ? "bg-emerald-50 text-emerald-800"
                    : "text-slate-600 hover:bg-slate-50 hover:text-slate-950",
                )}
              >
                <item.icon className="size-[18px]" strokeWidth={active ? 2.3 : 1.8} />
                {item.label}
              </Link>
            );
          })}
        </nav>

        <div className="mt-auto">
          <Link
            href="/settings/integrations"
            className={cn(
              "flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium",
              pathname.startsWith("/settings")
                ? "bg-emerald-50 text-emerald-800"
                : "text-slate-600 hover:bg-slate-50",
            )}
          >
            <Settings className="size-[18px]" />
            Settings & integrations
          </Link>
          <div className="mt-4 rounded-2xl border border-emerald-100 bg-emerald-50/70 p-4">
            <div className="flex items-center gap-2 text-xs font-semibold text-emerald-800">
              <ChartNoAxesCombined className="size-4" />
              Demo workspace
            </div>
            <p className="mt-2 text-xs leading-5 text-emerald-700">
              Sample data refreshes with the current date.
            </p>
          </div>
        </div>
      </aside>

      <div className="lg:pl-64">
        <header className="sticky top-0 z-30 flex h-16 items-center border-b border-slate-200/80 bg-white/90 px-4 backdrop-blur-md sm:px-6 lg:px-8">
          <Link href="/" className="mr-4 flex items-center gap-2 lg:hidden">
            <span className="grid size-8 place-items-center rounded-lg bg-emerald-600 text-white">
              <Leaf className="size-4" />
            </span>
            <span className="font-bold">Solaire</span>
          </Link>
          <div className="relative hidden max-w-md flex-1 md:block">
            <Search className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-slate-400" />
            <input
              aria-label="Search products, branches, or people"
              placeholder="Search products, branches, or people..."
              value={query}
              onChange={(event) => setQuery(event.target.value)}
              onKeyDown={(event) => {
                if (event.key === "Escape") setQuery("");
              }}
              className="h-10 w-full rounded-xl border border-slate-200 bg-slate-50/80 pl-10 pr-3 text-sm outline-none transition focus:border-emerald-400 focus:bg-white focus:ring-4 focus:ring-emerald-50"
            />
            {query.trim() && (
              <div className="absolute left-0 right-0 top-12 z-50 overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-xl shadow-slate-900/10">
                {matches.length ? (
                  <div className="p-2">
                    {matches.map((item) => (
                      <button
                        key={`${item.type}-${item.id}`}
                        onClick={() => {
                          router.push(item.href);
                          setQuery("");
                        }}
                        className="flex w-full items-center justify-between rounded-xl px-3 py-2.5 text-left hover:bg-slate-50"
                      >
                        <span>
                          <span className="block text-xs font-bold text-slate-900">{item.label}</span>
                          <span className="mt-0.5 block text-[11px] text-slate-400">{item.detail}</span>
                        </span>
                        <span className="rounded-full bg-emerald-50 px-2 py-1 text-[9px] font-bold uppercase tracking-wider text-emerald-700">
                          {item.type}
                        </span>
                      </button>
                    ))}
                  </div>
                ) : (
                  <p className="p-5 text-center text-xs text-slate-500">
                    No products, branches, or people match “{query}”.
                  </p>
                )}
              </div>
            )}
          </div>
          <div className="ml-auto flex items-center gap-2 sm:gap-4">
            <Link
              href="/alerts"
              aria-label="View alerts"
              className="relative grid size-10 place-items-center rounded-xl text-slate-500 hover:bg-slate-100"
            >
              <Bell className="size-5" />
              <span className="absolute right-2 top-2 size-2 rounded-full border-2 border-white bg-amber-500" />
            </Link>
            <div className="relative">
            <button
              aria-expanded={profileOpen}
              aria-label="Open account menu"
              onClick={() => setProfileOpen((open) => !open)}
              className="flex items-center gap-2 rounded-xl p-1.5 pr-2 hover:bg-slate-50"
            >
              <span className="grid size-8 place-items-center rounded-lg bg-slate-900 text-xs font-bold text-white">
                NC
              </span>
              <span className="hidden text-left sm:block">
                <span className="block text-xs font-semibold">Nora Clarke</span>
                <span className="block text-[10px] text-slate-400">Operations manager</span>
              </span>
              <ChevronDown className="hidden size-4 text-slate-400 sm:block" />
            </button>
            {profileOpen && (
              <div className="absolute right-0 top-12 z-50 w-52 rounded-xl border border-slate-200 bg-white p-2 shadow-xl shadow-slate-900/10">
                <p className="px-3 py-2 text-[11px] text-slate-400">Demo account</p>
                <Link href="/settings/integrations" onClick={() => setProfileOpen(false)} className="block rounded-lg px-3 py-2 text-xs font-semibold hover:bg-slate-50">
                  Workspace settings
                </Link>
                <form action="/api/auth/logout" method="post">
                  <button className="w-full rounded-lg px-3 py-2 text-left text-xs font-semibold text-rose-600 hover:bg-rose-50">
                    Sign out
                  </button>
                </form>
              </div>
            )}
            </div>
          </div>
        </header>

        <nav className="flex gap-1 overflow-x-auto border-b border-slate-200 bg-white px-3 py-2 lg:hidden">
          {navigation.slice(0, 5).map((item) => {
            const active = item.href === "/" ? pathname === "/" : pathname.startsWith(item.href);
            return (
              <Link
                key={item.href}
                href={item.href}
                className={cn(
                  "whitespace-nowrap rounded-lg px-3 py-2 text-xs font-semibold",
                  active ? "bg-emerald-50 text-emerald-800" : "text-slate-500",
                )}
              >
                {item.label}
              </Link>
            );
          })}
        </nav>
        <main className="mx-auto max-w-[1600px] px-4 py-6 sm:px-6 lg:px-8 lg:py-8">
          {children}
        </main>
      </div>
    </div>
  );
}
