"use client";

import {
  faBars,
  faTimes,
  faGauge,
  faImage,
  faStore,
  faLightbulb,
  faGear,
  faFolder,
  faAddressCard,
  faShareAlt,
  faEnvelope,
  faMagnifyingGlass,
  faArrowUpRightFromSquare,
  faRightFromBracket,
  faHouse,
  faBarsStaggered,
  faCircleUser,
} from "@fortawesome/free-solid-svg-icons";
import { faGoogle as faGoogleBrand } from "@fortawesome/free-brands-svg-icons";
import type { IconDefinition } from "@fortawesome/fontawesome-svg-core";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useMemo, useRef, useState } from "react";

interface NavItem {
  href: string;
  label: string;
  icon: IconDefinition;
  /** Additional pathname prefixes that should mark this item as active. */
  matchPrefixes?: string[];
}

interface NavGroup {
  label: string;
  items: NavItem[];
}

const NAV_GROUPS: NavGroup[] = [
  {
    label: "Overview",
    items: [{ href: "/admin", label: "Dashboard", icon: faGauge }],
  },
  {
    label: "Site Content",
    items: [
      {
        href: "/admin/home",
        label: "Homepage",
        icon: faHouse,
        matchPrefixes: [
          "/admin/hero",
          "/admin/about",
          "/admin/services",
          "/admin/bold",
          "/admin/watts",
        ],
      },
      { href: "/admin/navbar", label: "Navbar", icon: faBarsStaggered },
      { href: "/admin/projects", label: "Projects", icon: faFolder },
      { href: "/admin/watts-lights", label: "Watts Lights", icon: faLightbulb },
    ],
  },
  {
    label: "Communication",
    items: [
      {
        href: "/admin/contact-cards",
        label: "Contact Cards",
        icon: faAddressCard,
      },
      { href: "/admin/socials", label: "Social Links", icon: faShareAlt },
      { href: "/admin/email", label: "Email", icon: faEnvelope },
    ],
  },
  {
    label: "Settings",
    items: [
      { href: "/admin/seo", label: "SEO", icon: faMagnifyingGlass },
      { href: "/admin/google", label: "Google", icon: faGoogleBrand },
    ],
  },
];

const PATH_LABELS: Record<string, string> = {
  admin: "Admin",
  home: "Homepage",
  navbar: "Navbar",
  projects: "Projects",
  services: "Services",
  about: "About",
  hero: "Hero",
  bold: "Bold Products",
  watts: "Watts",
  "watts-lights": "Watts Lights",
  "contact-cards": "Contact Cards",
  socials: "Social Links",
  email: "Email",
  google: "Google",
  seo: "SEO",
};

function formatSegment(segment: string): string {
  if (PATH_LABELS[segment]) return PATH_LABELS[segment];
  return segment
    .split("-")
    .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
    .join(" ");
}

function useBreadcrumbs(pathname: string) {
  return useMemo(() => {
    const segments = pathname.split("/").filter(Boolean);
    return segments.map((segment, i) => ({
      label: formatSegment(segment),
      href: "/" + segments.slice(0, i + 1).join("/"),
      isLast: i === segments.length - 1,
    }));
  }, [pathname]);
}

export default function AdminLayout({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const [isNavOpen, setIsNavOpen] = useState(false);
  const [isUserMenuOpen, setIsUserMenuOpen] = useState(false);
  const userMenuRef = useRef<HTMLDivElement>(null);
  const breadcrumbs = useBreadcrumbs(pathname || "/admin");

  useEffect(() => {
    setIsNavOpen(false);
    setIsUserMenuOpen(false);
  }, [pathname]);

  useEffect(() => {
    const onClickOutside = (e: MouseEvent) => {
      if (
        userMenuRef.current &&
        !userMenuRef.current.contains(e.target as Node)
      ) {
        setIsUserMenuOpen(false);
      }
    };
    if (isUserMenuOpen) {
      document.addEventListener("mousedown", onClickOutside);
      return () => document.removeEventListener("mousedown", onClickOutside);
    }
  }, [isUserMenuOpen]);

  const isActiveItem = (item: NavItem): boolean => {
    if (item.href === "/admin") return pathname === "/admin";
    if (pathname === item.href) return true;
    if (pathname?.startsWith(item.href + "/")) return true;
    if (item.matchPrefixes?.some((p) => pathname === p || pathname?.startsWith(p + "/"))) {
      return true;
    }
    return false;
  };

  return (
    <div className="min-h-screen bg-slate-950 text-slate-100 font-sans antialiased">
      {/* Mobile overlay */}
      {isNavOpen && (
        <div
          className="fixed inset-0 z-30 bg-slate-950/80 backdrop-blur-sm md:hidden"
          onClick={() => setIsNavOpen(false)}
          aria-hidden="true"
        />
      )}

      {/* Sidebar */}
      <aside
        className={`fixed inset-y-0 left-0 z-40 flex w-64 flex-col border-r border-slate-800 bg-slate-900 transition-transform duration-200 ease-in-out ${
          isNavOpen ? "translate-x-0" : "-translate-x-full md:translate-x-0"
        }`}
      >
        <div className="flex h-16 items-center gap-2.5 border-b border-slate-800 px-5">
          <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-indigo-500 text-white shadow-sm">
            <span className="text-sm font-bold">N</span>
          </div>
          <div className="min-w-0">
            <div className="truncate text-sm font-semibold text-slate-100">
              Nitescape
            </div>
            <div className="truncate text-xs text-slate-400">Admin Console</div>
          </div>
        </div>

        <nav className="flex-1 overflow-y-auto px-3 py-4">
          <ul className="space-y-6">
            {NAV_GROUPS.map((group) => (
              <li key={group.label}>
                <div className="mb-2 px-3 text-xs font-semibold uppercase tracking-wider text-slate-500">
                  {group.label}
                </div>
                <ul className="space-y-0.5">
                  {group.items.map((item) => {
                    const active = isActiveItem(item);
                    return (
                      <li key={item.href}>
                        <Link
                          href={item.href}
                          className={`group relative flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors ${
                            active
                              ? "bg-indigo-500/10 text-indigo-300"
                              : "text-slate-400 hover:bg-slate-800/60 hover:text-slate-100"
                          }`}
                        >
                          {active && (
                            <span
                              aria-hidden="true"
                              className="absolute inset-y-1.5 left-0 w-0.5 rounded-full bg-indigo-400"
                            />
                          )}
                          <FontAwesomeIcon
                            icon={item.icon}
                            className={`h-4 w-4 shrink-0 ${
                              active
                                ? "text-indigo-300"
                                : "text-slate-500 group-hover:text-slate-300"
                            }`}
                          />
                          <span>{item.label}</span>
                        </Link>
                      </li>
                    );
                  })}
                </ul>
              </li>
            ))}
          </ul>
        </nav>

        <div className="border-t border-slate-800 px-3 py-3">
          <Link
            href="/"
            target="_blank"
            rel="noopener noreferrer"
            className="flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium text-slate-400 transition-colors hover:bg-slate-800/60 hover:text-slate-100"
          >
            <FontAwesomeIcon
              icon={faArrowUpRightFromSquare}
              className="h-3.5 w-3.5 shrink-0 text-slate-500"
            />
            <span>View site</span>
          </Link>
        </div>
      </aside>

      {/* Main column */}
      <div className="md:pl-64">
        {/* Topbar */}
        <header className="sticky top-0 z-30 flex h-16 items-center gap-3 border-b border-slate-800 bg-slate-950/80 px-4 backdrop-blur-md md:px-8">
          <button
            type="button"
            onClick={() => setIsNavOpen(true)}
            className="inline-flex h-9 w-9 items-center justify-center rounded-md text-slate-400 transition-colors hover:bg-slate-800 hover:text-slate-100 md:hidden"
            aria-label="Open navigation"
          >
            <FontAwesomeIcon icon={faBars} className="h-4 w-4" />
          </button>

          <nav aria-label="Breadcrumb" className="min-w-0 flex-1">
            <ol className="flex items-center gap-1.5 overflow-hidden whitespace-nowrap text-sm">
              {breadcrumbs.map((crumb, idx) => (
                <li key={crumb.href} className="flex items-center gap-1.5">
                  {idx > 0 && (
                    <span className="text-slate-600" aria-hidden="true">
                      /
                    </span>
                  )}
                  {crumb.isLast ? (
                    <span className="truncate font-medium text-slate-200">
                      {crumb.label}
                    </span>
                  ) : (
                    <Link
                      href={crumb.href}
                      className="truncate text-slate-400 transition-colors hover:text-slate-200"
                    >
                      {crumb.label}
                    </Link>
                  )}
                </li>
              ))}
            </ol>
          </nav>

          <div className="flex items-center gap-2">
            <Link
              href="/"
              target="_blank"
              rel="noopener noreferrer"
              className="hidden items-center gap-2 rounded-md border border-slate-800 bg-slate-900 px-3 py-1.5 text-xs font-medium text-slate-300 transition-colors hover:border-slate-700 hover:text-slate-100 sm:inline-flex"
            >
              <FontAwesomeIcon
                icon={faArrowUpRightFromSquare}
                className="h-3 w-3"
              />
              View site
            </Link>

            <div className="relative" ref={userMenuRef}>
              <button
                type="button"
                onClick={() => setIsUserMenuOpen((v) => !v)}
                className="inline-flex h-9 w-9 items-center justify-center rounded-md text-slate-400 transition-colors hover:bg-slate-800 hover:text-slate-100"
                aria-label="User menu"
                aria-haspopup="true"
                aria-expanded={isUserMenuOpen}
              >
                <FontAwesomeIcon icon={faCircleUser} className="h-5 w-5" />
              </button>
              {isUserMenuOpen && (
                <div
                  role="menu"
                  className="absolute right-0 mt-2 w-52 overflow-hidden rounded-lg border border-slate-800 bg-slate-900 shadow-lg shadow-black/40"
                >
                  <div className="border-b border-slate-800 px-3 py-2.5">
                    <div className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                      Signed in as
                    </div>
                    <div className="mt-0.5 truncate text-sm font-medium text-slate-200">
                      Administrator
                    </div>
                  </div>
                  <button
                    type="button"
                    role="menuitem"
                    onClick={() => {
                      window.location.href = "/api/auth/logout";
                    }}
                    className="flex w-full items-center gap-2.5 px-3 py-2 text-left text-sm font-medium text-slate-300 transition-colors hover:bg-slate-800 hover:text-slate-100"
                  >
                    <FontAwesomeIcon
                      icon={faRightFromBracket}
                      className="h-3.5 w-3.5 text-slate-500"
                    />
                    Sign out
                  </button>
                </div>
              )}
            </div>
          </div>
        </header>

        {/* Page content */}
        <main className="px-4 py-6 md:px-8 md:py-8">
          <div className="mx-auto w-full max-w-7xl">{children}</div>
        </main>
      </div>
    </div>
  );
}
