"use client";

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useRef, type ReactNode } from "react";
import { useAppDispatch, useAppSelector } from "@/core/hook";
import { logout as logoutAction, setAdmin } from "@/core/authSlice";
import {
  useLazyMeQuery,
  useLogoutMutation,
} from "@/services/auth-service";

const NAV = [
  { href: "/admin", label: "Dashboard", exact: true },
  { href: "/admin/reservations", label: "Reservations" },
  { href: "/admin/users", label: "Admins" },
];

export default function AdminShell({ children }: { children: ReactNode }) {
  const dispatch = useAppDispatch();
  const router = useRouter();
  const pathname = usePathname();
  const { token, admin, isAuthenticated, isInitializing } = useAppSelector(
    (s) => s.auth,
  );
  const [fetchMe] = useLazyMeQuery();
  const [logoutRequest] = useLogoutMutation();
  const verifiedRef = useRef(false);

  useEffect(() => {
    if (isInitializing) return;
    if (!isAuthenticated || !token) {
      router.replace(
        `/admin/login?next=${encodeURIComponent(pathname || "/admin")}`,
      );
      return;
    }
    if (verifiedRef.current) return;
    verifiedRef.current = true;
    fetchMe()
      .unwrap()
      .then((profile) => dispatch(setAdmin(profile)))
      .catch(() => {
        dispatch(logoutAction());
        router.replace("/admin/login");
      });
  }, [isInitializing, isAuthenticated, token, pathname, router, fetchMe, dispatch]);

  const handleLogout = async () => {
    try {
      await logoutRequest().unwrap();
    } catch {
      /* clear locally regardless */
    }
    dispatch(logoutAction());
    router.replace("/admin/login");
  };

  if (isInitializing || !isAuthenticated || !admin) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-[#fbf7f0]">
        <p className="text-xs uppercase tracking-[0.3em] text-[#d6ac63]">
          Loading…
        </p>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-[#fbf7f0]">
      <aside className="fixed inset-y-0 left-0 hidden lg:flex w-64 flex-col bg-[#1a1a1a] text-white">
        <div className="px-6 py-8 border-b border-white/10">
          <Link
            href="/"
            className="text-[#d6ac63] text-xs uppercase tracking-[0.3em] font-light"
          >
            Fauzan Resorts
          </Link>
          <p className="mt-1 text-[10px] uppercase tracking-[0.25em] text-white/50">
            Admin Portal
          </p>
        </div>
        <nav className="flex-1 px-3 py-6 space-y-1">
          {NAV.map((item) => {
            const active = item.exact
              ? pathname === item.href
              : pathname?.startsWith(item.href);
            return (
              <Link
                key={item.href}
                href={item.href}
                className={`block px-4 py-2.5 text-[11px] uppercase tracking-[0.2em] transition-colors ${
                  active
                    ? "bg-[#d6ac63]/15 text-[#d6ac63]"
                    : "text-white/70 hover:text-white hover:bg-white/5"
                }`}
              >
                {item.label}
              </Link>
            );
          })}
        </nav>
        <div className="px-6 py-5 border-t border-white/10 text-xs text-white/70">
          <p className="font-light truncate">{admin.fullname}</p>
          <p className="text-[10px] uppercase tracking-[0.2em] text-white/40 mt-1">
            {admin.role === "super_admin" ? "Super Admin" : "Admin"}
          </p>
          <button
            type="button"
            onClick={handleLogout}
            className="mt-4 text-[10px] uppercase tracking-[0.25em] text-[#d6ac63] hover:text-white transition-colors"
          >
            Sign out
          </button>
        </div>
      </aside>

      <header className="lg:hidden sticky top-0 z-30 bg-[#1a1a1a] text-white px-4 py-3 flex items-center justify-between">
        <Link
          href="/admin"
          className="text-[#d6ac63] text-[11px] uppercase tracking-[0.3em] font-light"
        >
          Fauzan Admin
        </Link>
        <button
          type="button"
          onClick={handleLogout}
          className="text-[10px] uppercase tracking-[0.25em] text-white/70"
        >
          Sign out
        </button>
      </header>

      <nav className="lg:hidden bg-white border-b border-[#d6ac63]/15 flex overflow-x-auto px-2">
        {NAV.map((item) => {
          const active = item.exact
            ? pathname === item.href
            : pathname?.startsWith(item.href);
          return (
            <Link
              key={item.href}
              href={item.href}
              className={`px-4 py-3 text-[11px] uppercase tracking-[0.2em] whitespace-nowrap ${
                active ? "text-[#d6ac63] border-b-2 border-[#d6ac63]" : "text-gray-600"
              }`}
            >
              {item.label}
            </Link>
          );
        })}
      </nav>

      <main className="lg:pl-64">
        <div className="px-6 py-8 lg:px-12 lg:py-12 max-w-6xl">{children}</div>
      </main>
    </div>
  );
}
