"use client";

import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import {
  BarChart3,
  BatteryCharging,
  Bike,
  CalendarClock,
  CarFront,
  ChevronDown,
  CircleHelp,
  ClipboardList,
  FilePlus2,
  FileText,
  Gift,
  Layers3,
  List,
  LogOut,
  MapPin,
  Menu,
  PackagePlus,
  ShieldCheck,
  Users,
  UserCircle,
  Wrench,
  X,
} from "lucide-react";
import { useEffect, useState } from "react";
import { logoutAdmin } from "@/lib/admin-api";

type AdminShellProps = {
  children: React.ReactNode;
  title: string;
  lead?: string;
};

type AdminNavChild = {
  href: string;
  label: string;
  icon: React.ComponentType<{ className?: string }>;
};

type AdminNavItem =
  | AdminNavChild
  | {
      label: string;
      icon: React.ComponentType<{ className?: string }>;
      children: AdminNavChild[];
    };

const links: AdminNavItem[] = [
  { href: "/admin", label: "Dashboard", icon: BarChart3 },
  { href: "/admin/analytics", label: "Analytics", icon: BarChart3 },
  { href: "/admin/profile", label: "Profile", icon: UserCircle },
  { href: "/admin/users", label: "Users", icon: Users },
  {
    label: "Order management",
    icon: ClipboardList,
    children: [
      { href: "/admin/orders", label: "All orders", icon: ClipboardList },
      { href: "/admin/orders?status=placed", label: "Placed orders", icon: CalendarClock },
      { href: "/admin/orders?status=confirmed", label: "Confirmed orders", icon: ShieldCheck },
      { href: "/admin/orders?status=in_progress", label: "In progress orders", icon: Wrench },
      { href: "/admin/orders?status=completed", label: "Completed orders", icon: PackagePlus },
      { href: "/admin/orders?status=cancelled", label: "Cancelled orders", icon: X },
    ],
  },
  { href: "/admin/locations", label: "Locations", icon: MapPin },
  { href: "/admin/vehicle-tiers", label: "Vehicle tiers", icon: Layers3 },
  { href: "/admin/add-on-items", label: "Add-on items", icon: Gift },
  {
    label: "Packages",
    icon: PackagePlus,
    children: [
      { href: "/admin/service-packages", label: "Service packages", icon: PackagePlus },
      { href: "/admin/amc-packages", label: "AMC packages", icon: ShieldCheck },
      {
        href: "/admin/car-ac-service-packages",
        label: "Car AC service",
        icon: CarFront,
      },
      {
        href: "/admin/engine-repair-packages",
        label: "Engine repair",
        icon: Wrench,
      },
      {
        href: "/admin/battery-service-packages",
        label: "Battery service",
        icon: BatteryCharging,
      },
      {
        href: "/admin/tyre-wheel-service-packages",
        label: "Tyre & wheel",
        icon: Wrench,
      },
    ],
  },
  {
    label: "Blogs",
    icon: FileText,
    children: [
      { href: "/admin/blogs", label: "Blog list", icon: List },
      { href: "/admin/blogs/new", label: "Add blog", icon: FilePlus2 },
    ],
  },
  { href: "/admin/faqs", label: "FAQs", icon: CircleHelp },
  {
    label: "Cars",
    icon: CarFront,
    children: [
      { href: "/admin/car-logos", label: "Car companies", icon: CarFront },
      { href: "/admin/car-models", label: "Car models", icon: List },
    ],
  },
  {
    label: "Bikes",
    icon: Bike,
    children: [
      { href: "/admin/bike-logos", label: "Bike companies", icon: Bike },
      { href: "/admin/bike-models", label: "Bike models", icon: List },
    ],
  },
];

const adminSidebarGroupsKey = "admin-sidebar-open-groups";

function normalizePath(pathname: string) {
  return pathname !== "/" ? pathname.replace(/\/+$/, "") : pathname;
}

function isAdminLinkActive(currentPath: string, href: string) {
  const [hrefPath, hrefQuery] = href.split("?");
  const [pathname, currentQuery] = currentPath.split("?");

  if (hrefQuery) {
    return currentPath === href;
  }

  if (currentQuery && pathname === hrefPath) {
    return false;
  }

  if (href === "/admin") {
    return pathname === href;
  }

  if (hrefPath === "/admin/blogs") {
    return (
      pathname === hrefPath ||
      (pathname.startsWith(`${hrefPath}/`) && pathname !== "/admin/blogs/new")
    );
  }

  return pathname === hrefPath || pathname.startsWith(`${hrefPath}/`);
}

export function AdminShell({ children, title, lead }: AdminShellProps) {
  const pathname = normalizePath(usePathname());
  const searchParams = useSearchParams();
  const currentPath = searchParams.toString() ? `${pathname}?${searchParams.toString()}` : pathname;
  const router = useRouter();
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [showExitAlert, setShowExitAlert] = useState(false);
  const [openGroups, setOpenGroups] = useState<string[]>([]);

  useEffect(() => {
    try {
      const storedGroups = window.localStorage.getItem(adminSidebarGroupsKey);

      if (storedGroups) {
        const parsedGroups = JSON.parse(storedGroups);

        if (Array.isArray(parsedGroups)) {
          setOpenGroups(parsedGroups.filter((group): group is string => typeof group === "string"));
        }
      }
    } catch {
      setOpenGroups([]);
    }
  }, []);

  useEffect(() => {
    window.localStorage.setItem(adminSidebarGroupsKey, JSON.stringify(openGroups));
  }, [openGroups]);

  useEffect(() => {
    const activeGroup = links.find(
      (link) =>
        "children" in link &&
        link.children.some(({ href }) => isAdminLinkActive(currentPath, href)),
    );

    if (activeGroup && "children" in activeGroup) {
      setOpenGroups((current) =>
        current.includes(activeGroup.label) ? current : [...current, activeGroup.label],
      );
    }
  }, [currentPath]);

  function toggleGroup(label: string) {
    setOpenGroups((current) =>
      current.includes(label) ? current.filter((group) => group !== label) : [...current, label],
    );
  }

  async function confirmExit() {
    await logoutAdmin().catch((error: unknown) => {
      console.warn("Failed to end admin session on server", error);
    });
    router.replace("/admin/login");
  }

  const sidebar = (
    <aside className="flex h-full max-h-dvh w-72 flex-col border-r border-border bg-white">
      <div className="flex h-16 shrink-0 items-center justify-between border-b border-border px-5">
        <Link href="/admin" className="min-w-0">
          <p className="text-xs font-black uppercase tracking-[0.18em] text-primary">
            Ride N Revive
          </p>
          <p className="text-lg font-black tracking-tight text-foreground">Admin Panel</p>
        </Link>
        <button
          type="button"
          onClick={() => setSidebarOpen(false)}
          className="grid h-9 w-9 place-items-center rounded-md text-muted-foreground hover:bg-slate-100 lg:hidden"
          aria-label="Close admin menu"
        >
          <X className="h-5 w-5" />
        </button>
      </div>

      <nav className="min-h-0 flex-1 space-y-1 overflow-y-auto overscroll-contain p-4">
        {links.map((link) => {
          const Icon = link.icon;

          if ("children" in link) {
            const groupActive = link.children.some(({ href }) =>
              isAdminLinkActive(currentPath, href),
            );
            const groupOpen = openGroups.includes(link.label);

            return (
              <div key={link.label} className="space-y-1">
                <button
                  type="button"
                  onClick={() => toggleGroup(link.label)}
                  aria-expanded={groupOpen}
                  className={`flex h-11 w-full items-center gap-3 rounded-md px-3 text-left text-sm font-bold transition ${
                    groupActive
                      ? "bg-primary/10 text-primary"
                      : "text-muted-foreground hover:bg-slate-100 hover:text-foreground"
                  }`}
                >
                  <Icon className="h-4 w-4" />
                  <span className="min-w-0 flex-1 truncate">{link.label}</span>
                  <ChevronDown
                    className={`h-4 w-4 shrink-0 transition-transform ${
                      groupOpen ? "rotate-180" : ""
                    }`}
                  />
                </button>

                {groupOpen ? (
                  <div className="ml-4 space-y-1 border-l border-border pl-3">
                    {link.children.map(({ href, label, icon: ChildIcon }) => {
                      const isActive = isAdminLinkActive(currentPath, href);

                      return (
                        <Link
                          key={href}
                          href={href}
                          className={`flex h-10 items-center gap-3 rounded-md px-3 text-sm font-bold transition ${
                            isActive
                              ? "bg-primary text-primary-foreground shadow-sm"
                              : "text-muted-foreground hover:bg-slate-100 hover:text-foreground"
                          }`}
                        >
                          <ChildIcon className="h-4 w-4" />
                          <span className="min-w-0 truncate">{label}</span>
                        </Link>
                      );
                    })}
                  </div>
                ) : null}
              </div>
            );
          }

          const isActive = isAdminLinkActive(pathname, link.href);

          return (
            <Link
              key={link.href}
              href={link.href}
              className={`flex h-11 items-center gap-3 rounded-md px-3 text-sm font-bold transition ${
                isActive
                  ? "bg-primary text-primary-foreground shadow-sm"
                  : "text-muted-foreground hover:bg-slate-100 hover:text-foreground"
              }`}
            >
              <Icon className="h-4 w-4" />
              {link.label}
            </Link>
          );
        })}
      </nav>

      <div className="shrink-0 border-t border-border p-4">
        <div className="mb-3 rounded-md bg-slate-50 p-3">
          <div className="flex items-center gap-2 text-xs font-black uppercase tracking-[0.14em] text-primary">
            <ShieldCheck className="h-4 w-4" />
            Signed in
          </div>
          <p className="mt-1 truncate text-sm font-bold text-foreground">ridenrevive@admin.com</p>
        </div>
        <button
          type="button"
          onClick={() => setShowExitAlert(true)}
          className="flex h-10 w-full items-center justify-center gap-2 rounded-md border border-border bg-white text-sm font-bold text-muted-foreground transition hover:bg-slate-100 hover:text-foreground"
        >
          <LogOut className="h-4 w-4" />
          Sign out
        </button>
      </div>
    </aside>
  );

  return (
    <section className="min-h-screen bg-slate-50 font-['Space_Grotesk'] text-foreground">
      <div className="hidden lg:fixed lg:inset-y-0 lg:left-0 lg:z-30 lg:block">{sidebar}</div>

      {sidebarOpen ? (
        <div className="fixed inset-0 z-50 lg:hidden">
          <button
            type="button"
            className="absolute inset-0 bg-slate-950/40"
            onClick={() => setSidebarOpen(false)}
            aria-label="Close admin menu overlay"
          />
          <div className="relative h-full max-w-[calc(100vw-2rem)]">{sidebar}</div>
        </div>
      ) : null}

      <div className="lg:pl-72">
        <header className="sticky top-0 z-20 flex h-16 items-center justify-between border-b border-border bg-white/95 px-4 backdrop-blur md:px-6">
          <div className="flex min-w-0 items-center gap-3">
            <button
              type="button"
              onClick={() => setSidebarOpen(true)}
              className="grid h-10 w-10 place-items-center rounded-md border border-border text-muted-foreground hover:bg-slate-100 lg:hidden"
              aria-label="Open admin menu"
            >
              <Menu className="h-5 w-5" />
            </button>
            <div className="min-w-0">
              <h1 className="truncate text-xl font-black tracking-tight text-foreground md:text-2xl">
                {title}
              </h1>
              {lead ? (
                <p className="hidden max-w-2xl truncate text-xs font-semibold text-muted-foreground md:block">
                  {lead}
                </p>
              ) : null}
            </div>
          </div>
        </header>

        <main className="px-4 py-6 md:px-6 lg:px-8">
          <div className="mx-auto max-w-7xl">{children}</div>
        </main>
      </div>

      {showExitAlert ? (
        <div className="fixed inset-0 z-[70] grid place-items-center bg-slate-950/45 px-4">
          <div className="w-full max-w-sm rounded-lg border border-border bg-white p-5 shadow-2xl">
            <div className="grid h-11 w-11 place-items-center rounded-md bg-primary/10 text-primary">
              <LogOut className="h-5 w-5" />
            </div>
            <h2 className="mt-4 text-xl font-black tracking-tight text-foreground">
              End admin session?
            </h2>
            <p className="mt-2 text-sm leading-6 text-muted-foreground">
              Signing out will expire this admin session. Opening admin pages again will require a
              fresh login.
            </p>
            <div className="mt-5 flex justify-end gap-2">
              <button
                type="button"
                onClick={() => setShowExitAlert(false)}
                className="h-10 rounded-md border border-border px-4 text-sm font-black text-muted-foreground transition hover:bg-slate-100 hover:text-foreground"
              >
                Cancel
              </button>
              <button
                type="button"
                onClick={confirmExit}
                className="h-10 rounded-md bg-primary px-4 text-sm font-black text-primary-foreground transition hover:opacity-95"
              >
                Sign out
              </button>
            </div>
          </div>
        </div>
      ) : null}
    </section>
  );
}
