"use client";

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
import {
  CreditCard,
  FileText,
  FolderTree,
  LayoutDashboard,
  LogOut,
  Mail,
  Menu,
  Package,
  Settings,
  ShoppingBag,
  Store,
  Users,
  Warehouse,
  X,
} from "lucide-react";
import { useAuth } from "@/context/auth-context";
import { ThemeToggle } from "@/components/ui/ThemeToggle";
import { adminPageEnter } from "@/lib/motion";
import { cn } from "@/lib/cn";

const nav = [
  {
    title: "Dashboard",
    items: [
      { href: "/admin", label: "Overview", icon: LayoutDashboard },
      { href: "/admin/orders", label: "Orders", icon: ShoppingBag },
      { href: "/admin/customers", label: "Customers", icon: Users },
    ],
  },
  {
    title: "Catalog",
    items: [
      { href: "/admin/products", label: "Products", icon: Package },
      { href: "/admin/categories", label: "Categories", icon: FolderTree },
      { href: "/admin/inventory", label: "Inventory", icon: Warehouse },
    ],
  },
  {
    title: "Content",
    items: [
      { href: "/admin/pages", label: "Pages & policies", icon: FileText },
    ],
  },
  {
    title: "Settings",
    items: [
      { href: "/admin/settings", label: "General & branding", icon: Settings },
      { href: "/admin/settings/stripe", label: "Stripe payments", icon: CreditCard },
      { href: "/admin/settings/email", label: "SMTP / email", icon: Mail },
    ],
  },
];

function AdminGateMessage({ children }: { children: React.ReactNode }) {
  return (
    <div className="flex min-h-screen items-center justify-center bg-background text-sm text-muted">
      <div className="flex flex-col items-center gap-3">
        <div className="h-9 w-9 animate-spin rounded-full border-2 border-border border-t-emerald-500" />
        {children}
      </div>
    </div>
  );
}

/** Theme-aware admin shell with role guard. */
export function AdminShell({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const { user, loading, logout } = useAuth();
  const router = useRouter();
  const [mobileOpen, setMobileOpen] = useState(false);
  const reduceMotion = useReducedMotion();

  useEffect(() => {
    if (loading) return;
    if (!user) {
      router.replace(`/login?next=${encodeURIComponent(pathname)}`);
      return;
    }
    if (user.role !== "admin") router.replace("/account");
  }, [user, loading, router, pathname]);

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

  if (loading) {
    return <AdminGateMessage>Checking admin access…</AdminGateMessage>;
  }

  if (!user) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-background text-sm text-muted">
        Redirecting to login…
      </div>
    );
  }

  if (user.role !== "admin") {
    return (
      <div className="flex min-h-screen items-center justify-center bg-background text-sm text-muted">
        Admin access required. Redirecting…
      </div>
    );
  }

  const Sidebar = (
    <aside className="flex h-full w-[260px] flex-col border-r border-border bg-card">
      <div className="flex h-16 shrink-0 items-center gap-3 border-b border-border px-5">
        <span className="inline-flex h-9 w-9 items-center justify-center rounded-xl bg-emerald-500 text-sm font-bold text-zinc-950">
          FM
        </span>
        <div>
          <p className="text-sm font-semibold text-foreground">BhoFit Admin</p>
          <p className="text-[11px] text-muted">Control center</p>
        </div>
      </div>

      <nav className="min-h-0 flex-1 space-y-6 overflow-y-auto px-3 py-5">
        {nav.map((group) => (
          <div key={group.title}>
            <p className="mb-2 px-3 text-[10px] font-semibold uppercase tracking-[0.16em] text-muted">
              {group.title}
            </p>
            <div className="space-y-1">
              {group.items.map((link) => {
                const Icon = link.icon;
                const active =
                  link.href === "/admin"
                    ? pathname === "/admin"
                    : pathname === link.href ||
                      (link.href !== "/admin/settings" &&
                        pathname.startsWith(link.href));
                return (
                  <Link
                    key={link.href}
                    href={link.href}
                    className={cn(
                      "flex items-center gap-2.5 rounded-xl px-3 py-2.5 text-sm transition-all duration-300 ease-out",
                      active
                        ? "bg-emerald-500/15 font-medium text-emerald-700 shadow-sm dark:text-emerald-300"
                        : "text-muted hover:translate-x-0.5 hover:bg-surface hover:text-foreground",
                    )}
                  >
                    <Icon className="h-4 w-4 shrink-0" />
                    {link.label}
                  </Link>
                );
              })}
            </div>
          </div>
        ))}
      </nav>

      <div className="shrink-0 border-t border-border p-3">
        <Link
          href="/"
          className="mb-1 flex items-center gap-2.5 rounded-xl px-3 py-2.5 text-sm text-muted hover:bg-surface hover:text-foreground"
        >
          <Store className="h-4 w-4" />
          View storefront
        </Link>
        <button
          type="button"
          onClick={async () => {
            await logout();
            router.push("/login");
          }}
          className="flex w-full items-center gap-2.5 rounded-xl px-3 py-2.5 text-sm text-muted hover:bg-surface hover:text-foreground"
        >
          <LogOut className="h-4 w-4" />
          Sign out
        </button>
      </div>
    </aside>
  );

  return (
    <div className="min-h-screen bg-background text-foreground">
      <div className="fixed inset-y-0 left-0 z-40 hidden w-[260px] lg:block">
        {Sidebar}
      </div>

      {mobileOpen ? (
        <div className="fixed inset-0 z-50 flex lg:hidden">
          <button
            type="button"
            className="absolute inset-0 bg-black/50 dark:bg-black/60"
            aria-label="Close menu"
            onClick={() => setMobileOpen(false)}
          />
          <div className="relative z-10 h-full w-[260px] shadow-2xl">{Sidebar}</div>
        </div>
      ) : null}

      <div className="flex min-h-screen min-w-0 flex-col lg:pl-[260px]">
        <header className="sticky top-0 z-30 flex h-16 shrink-0 items-center justify-between border-b border-border bg-background/95 px-4 backdrop-blur-md sm:px-6">
          <div className="flex items-center gap-3">
            <button
              type="button"
              className="inline-flex h-10 w-10 items-center justify-center rounded-xl border border-border text-foreground lg:hidden"
              onClick={() => setMobileOpen(true)}
              aria-label="Open menu"
            >
              {mobileOpen ? <X className="h-4 w-4" /> : <Menu className="h-4 w-4" />}
            </button>
            <div>
              <p className="text-sm font-medium text-foreground">
                Welcome, {user.name}
              </p>
              <p className="text-xs text-muted">{user.email}</p>
            </div>
          </div>
          <ThemeToggle />
        </header>
        <div className="min-w-0 flex-1 overflow-x-clip px-4 py-6 text-foreground sm:px-6 lg:px-8">
          {reduceMotion ? (
            <div key={pathname}>{children}</div>
          ) : (
            <AnimatePresence mode="wait">
              <motion.div
                key={pathname}
                initial={adminPageEnter.initial}
                animate={adminPageEnter.animate}
                exit={adminPageEnter.exit}
                transition={adminPageEnter.transition}
                className="min-w-0"
              >
                {children}
              </motion.div>
            </AnimatePresence>
          )}
        </div>
      </div>
    </div>
  );
}
