"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import {
  Bell,
  BookOpenText,
  ChevronDown,
  ChevronRight,
  CircleHelp,
  FolderKanban,
  Image as ImageIcon,
  ListTree,
  LayoutDashboard,
  LockKeyhole,
  LogOut,
  Mailbox,
  Menu,
  PencilLine,
  Search,
  Settings,
  Share2,
  Users,
} from "lucide-react";

import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

type AdminPanelShellProps = {
  children: React.ReactNode;
};

const adminNavItems = [
  { label: "Dashboard", href: "/scs-admin/dashboard", icon: LayoutDashboard },
  { label: "Users", href: "/scs-admin/users", icon: Users },
  {
    label: "Hero Sections",
    href: "/scs-admin/career-groups",
    icon: FolderKanban,
    children: [
      {
        label: "Working at Singh",
        href: "/scs-admin/career-groups?type=working_at_singh",
      },
      {
        label: "Tradition of Excellence",
        href: "/scs-admin/career-groups?type=tradition_of_excellence",
      },
      {
        label: "About Us",
        href: "/scs-admin/career-groups?type=about_us",
      },
    ],
  },
  {
    label: "Department Pages",
    href: "/scs-admin/department-pages",
    icon: PencilLine,
  },
  {
    label: "Job Categories",
    href: "/scs-admin/job-categories",
    icon: ListTree,
  },
  {
    label: "Blogs",
    href: "/scs-admin/blogs",
    icon: BookOpenText,
    children: [
      { label: "Blog Categories", href: "/scs-admin/blog-categories" },
      { label: "Blog Tags", href: "/scs-admin/blog-tags" },
      { label: "Blog Listing", href: "/scs-admin/blogs" },
    ],
  },
  { label: "Banners", href: "/scs-admin/banners", icon: ImageIcon },
  { label: "Social Links", href: "/scs-admin/social-links", icon: Share2 },
  {
    label: "Contact & Inquiries",
    href: "/scs-admin/contact-submission",
    icon: Mailbox,
    children: [
      { label: "Contact Settings", href: "/scs-admin/contact-settings" },
      { label: "Contact Submissions", href: "/scs-admin/contact-submission" },
    ],
  },
];

const adminBottomNavItems = [
  { label: "Settings", href: "/scs-admin/settings", icon: Settings },
  { label: "Help Center", href: "/scs-admin/help-center", icon: CircleHelp },
];

const mobileAdminNavItems = [
  ...adminNavItems.flatMap((item) => item.children || [item]),
  ...adminBottomNavItems,
];

export default function AdminPanelShell({ children }: AdminPanelShellProps) {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const router = useRouter();
  const [user, setUser] = useState<{ name?: string; email?: string } | null>(
    null,
  );

  useEffect(() => {
    const token = localStorage.getItem("scs_admin_token");
    const storedUser = localStorage.getItem("scs_admin_user");

    if (!token) {
      router.replace("/scs-admin/login");
      return;
    }

    if (storedUser) {
      try {
        setUser(JSON.parse(storedUser) as { name?: string; email?: string });
      } catch {
        setUser(null);
      }
    }
  }, [router]);

  const handleLogout = () => {
    localStorage.removeItem("scs_admin_token");
    localStorage.removeItem("scs_admin_user");
    router.push("/scs-admin/login");
  };

  const isHrefActive = (href: string) => {
    const [hrefPathname, hrefSearch = ""] = href.split("?");

    if (pathname !== hrefPathname) {
      return false;
    }

    return hrefSearch
      ? searchParams.toString() === hrefSearch
      : searchParams.toString() === "";
  };

  return (
    <div className="min-h-screen bg-[#F7F2EC] text-[#2B221D]">
      <div className="grid min-h-screen lg:grid-cols-[276px_minmax(0,1fr)]">
        <aside className="hidden border-r border-[#1D1D1D] bg-[#1D1D1D] px-6 pb-7 text-[#FBF7F1] lg:flex lg:flex-col">
          <div className="-mx-6 mb-8 flex h-[58px] items-center justify-center border-b border-white/12 px-6">
            <Link
              href="/scs-admin/dashboard"
              className="inline-flex items-center"
            >
              <img
                src="/Logo-image.png"
                alt="Singh"
                width={118}
                height={36}
                className="h-8 w-auto object-contain brightness-0 invert"
              />
            </Link>
          </div>

          <nav className="flex-1 space-y-2" aria-label="Admin sidebar">
            {adminNavItems.map(({ label, href, icon: Icon }) => {
              const item = adminNavItems.find(
                (navItem) => navItem.href === href,
              );
              const children = item?.children;
              const isActive =
                isHrefActive(href) ||
                !!children?.some((child) => isHrefActive(child.href));

              if (children) {
                return (
                  <Collapsible key={href} defaultOpen={isActive}>
                    <CollapsibleTrigger
                      className={`flex w-full items-center gap-3 px-4 py-3 text-sm font-medium transition-colors ${
                        isActive
                          ? "rounded-2xl bg-[#E8E1D0] text-[#3A2D27] shadow-[0_8px_20px_rgba(58,45,39,0.12)]"
                          : "rounded-2xl text-[#F5ECE5] hover:bg-white/8 hover:text-white"
                      }`}
                    >
                      <Icon className="size-4" />
                      <span className="flex-1 text-left">{label}</span>
                      <ChevronRight className="size-4 transition-transform data-[state=open]:rotate-90" />
                    </CollapsibleTrigger>
                    <CollapsibleContent className="mt-2 space-y-1 pl-6">
                      {children.map((child) => {
                        const isChildActive = isHrefActive(child.href);

                        return (
                          <Link
                            key={child.href}
                            href={child.href}
                            className={`flex items-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium transition-colors ${
                              isChildActive
                                ? "bg-white/14 text-white"
                                : "text-[#D9CEC4] hover:bg-white/8 hover:text-white"
                            }`}
                          >
                            <span
                              className={`size-1.5 rounded-full ${
                                isChildActive ? "bg-white" : "bg-[#B5A169]"
                              }`}
                            />
                            <span>{child.label}</span>
                          </Link>
                        );
                      })}
                    </CollapsibleContent>
                  </Collapsible>
                );
              }

              return (
                <Link
                  key={href}
                  href={href}
                  className={`flex items-center gap-3 px-4 py-3 text-sm font-medium transition-colors ${
                    isActive
                      ? "rounded-2xl bg-[#E8E1D0] text-[#3A2D27] shadow-[0_8px_20px_rgba(58,45,39,0.12)]"
                      : "rounded-2xl text-[#F5ECE5] hover:bg-white/8 hover:text-white"
                  }`}
                >
                  <Icon className="size-4" />
                  <span>{label}</span>
                </Link>
              );
            })}
          </nav>

          <nav
            className="mt-6 space-y-2 border-t border-white/12 pt-6"
            aria-label="Admin sidebar secondary"
          >
            {adminBottomNavItems.map(({ label, href, icon: Icon }) => {
              const isActive = isHrefActive(href);

              return (
                <Link
                  key={href}
                  href={href}
                  className={`flex items-center gap-3 px-4 py-3 text-sm font-medium transition-colors ${
                    isActive
                      ? "rounded-2xl bg-[#E8E1D0] text-[#3A2D27] shadow-[0_8px_20px_rgba(58,45,39,0.12)]"
                      : "rounded-2xl text-[#F5ECE5] hover:bg-white/8 hover:text-white"
                  }`}
                >
                  <Icon className="size-4" />
                  <span>{label}</span>
                </Link>
              );
            })}
          </nav>
        </aside>

        <div className="flex min-h-screen flex-col">
          <header className="border-b border-[#E3D8CC] bg-[#FCF9F4]">
            <div className="flex flex-wrap items-center justify-between gap-3 px-4 py-2 sm:px-6 lg:h-[58px] lg:flex-nowrap lg:px-8 lg:py-0">
              <div className="flex items-center gap-3">
                <button
                  type="button"
                  className="inline-flex size-9 items-center justify-center rounded-xl bg-white text-[#5B4A42] shadow-[0_4px_14px_rgba(58,45,39,0.08)] lg:hidden"
                  aria-label="Admin menu"
                >
                  <Menu className="size-4" />
                </button>
                <Link
                  href="/scs-admin/dashboard"
                  className="hidden items-center lg:inline-flex"
                >
                  <p className="text-[1.35rem] font-semibold tracking-[-0.02em] text-[#2B221D]">
                    Welcome Back,{" "}
                    <span className="text-[#B5A169]">
                      {user?.name || "Admin"}!
                    </span>
                  </p>
                </Link>
              </div>

              <div className="flex w-full items-center gap-3 sm:w-auto">
                <div className="relative min-w-0 flex-1 sm:w-[280px] sm:flex-none">
                  <Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-[#99877C]" />
                  <input
                    type="search"
                    placeholder="Search admin panel"
                    className="h-9 w-full rounded-xl bg-white pl-10 pr-4 text-sm text-[#2B221D] outline-none shadow-[0_4px_14px_rgba(58,45,39,0.06)] transition-colors placeholder:text-[#99877C] focus:bg-[#FFFDFC]"
                  />
                </div>

                <button
                  type="button"
                  className="relative inline-flex size-9 items-center justify-center rounded-xl bg-white text-[#5B4A42] shadow-[0_4px_14px_rgba(58,45,39,0.06)] transition-colors hover:bg-[#FFFDFC] hover:text-[#B5A169]"
                  aria-label="Notifications"
                >
                  <Bell className="size-4" />
                  <span className="absolute right-2 top-2 size-2 rounded-full bg-[#B5A169]" />
                </button>

                <DropdownMenu>
                  <DropdownMenuTrigger asChild>
                    <button
                      type="button"
                      className="hidden items-center gap-2.5 rounded-xl bg-white px-3 py-1.5 shadow-[0_4px_14px_rgba(58,45,39,0.06)] sm:flex"
                      aria-label="Account menu"
                    >
                      <div className="flex size-8 items-center justify-center rounded-xl bg-[#B5A169] text-xs font-semibold text-[#5A4439]">
                        {(user?.name || "Admin").slice(0, 2).toUpperCase()}
                      </div>
                      <div className="min-w-0 text-left">
                        <p className="truncate text-sm font-semibold text-[#2B221D]">
                          {user?.name || "Admin"}
                        </p>
                        <p className="truncate text-xs text-[#8A7A6D]">
                          {user?.email || "admin@singhcareers.com"}
                        </p>
                      </div>
                      <ChevronDown className="size-4 text-[#8A7A6D]" />
                    </button>
                  </DropdownMenuTrigger>
                  <DropdownMenuContent
                    align="end"
                    className="w-[245px] rounded-[18px] border border-[#E1D6CB] bg-[#FCF9F4] p-0 shadow-[0_18px_40px_rgba(58,45,39,0.12)]"
                  >
                    <div className="px-5 py-4">
                      <p className="text-[1.05rem] font-semibold text-[#2B221D]">
                        {user?.name || "Admin"}
                      </p>
                      <p className="mt-1 text-sm text-[#8A7A6D]">Account</p>
                    </div>
                    <DropdownMenuSeparator className="mx-0 my-0 bg-[#ECE3D9]" />
                    <DropdownMenuItem
                      asChild
                      className="rounded-none px-5 py-3 text-[15px] text-[#2B221D] focus:bg-[#F3E8DE] focus:text-[#2B221D]"
                    >
                      <Link href="/scs-admin/manage-profile">
                        <PencilLine className="size-4 text-[#7D6A60]" />
                        Manage Profile
                      </Link>
                    </DropdownMenuItem>
                    <DropdownMenuItem
                      asChild
                      className="rounded-none px-5 py-3 text-[15px] text-[#2B221D] focus:bg-[#F3E8DE] focus:text-[#2B221D]"
                    >
                      <Link href="/scs-admin/change-password">
                        <LockKeyhole className="size-4 text-[#7D6A60]" />
                        Change Password
                      </Link>
                    </DropdownMenuItem>
                    <DropdownMenuSeparator className="mx-0 my-0 bg-[#ECE3D9]" />
                    <DropdownMenuItem
                      onClick={handleLogout}
                      variant="destructive"
                      className="rounded-none px-5 py-3 text-[15px] text-[#8D4F48] focus:bg-[#F6E9E6] focus:text-[#8D4F48] data-[variant=destructive]:text-[#8D4F48] data-[variant=destructive]:focus:bg-[#F6E9E6] data-[variant=destructive]:focus:text-[#8D4F48]"
                    >
                      <LogOut className="size-4 !text-[#8D4F48]" />
                      Logout
                    </DropdownMenuItem>
                  </DropdownMenuContent>
                </DropdownMenu>
              </div>
            </div>

            <div className="border-t border-[#E8DDD2] px-4 py-2 sm:px-6 lg:hidden">
              <nav
                className="flex gap-2 overflow-x-auto"
                aria-label="Admin mobile navigation"
              >
                {mobileAdminNavItems.map(({ label, href }) => {
                  const isActive = isHrefActive(href);

                  return (
                    <Link
                      key={href}
                      href={href}
                      className={`shrink-0 rounded-xl px-3 py-1.5 text-xs font-medium transition-colors ${
                        isActive
                          ? "bg-[#E7D7CB] text-[#4D3D35]"
                          : "bg-white text-[#7C6C61] shadow-[0_4px_14px_rgba(58,45,39,0.05)]"
                      }`}
                    >
                      {label}
                    </Link>
                  );
                })}
              </nav>
            </div>
          </header>

          <main className="flex-1 px-4 py-5 sm:px-6 lg:px-8 lg:py-7">
            {children}
          </main>

          <footer className="border-t border-[#E3D8CC] bg-[#FCF9F4] px-4 py-4 text-sm text-[#7A6B60] sm:px-6 lg:px-8">
            <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
              <p>© 2026 Singh Organization. All rights reserved.</p>
              <p>Built with the Singh brand palette for content operations.</p>
            </div>
          </footer>
        </div>
      </div>
    </div>
  );
}
