import { Link, Navigate, NavLink, Outlet, useNavigate } from "react-router-dom";
import { useAdminT } from "../admin/useAdminT";
import { clearToken, getToken } from "../admin/token";
import { adminUiPrefix } from "../adminPaths";
import { useAdminRouterMode } from "../adminRouterMode";

export function AdminLayout() {
  const t = useAdminT();
  const mode = useAdminRouterMode();
  const nav = useNavigate();
  const token = getToken();
  const loginTo = mode === "basename" ? "login" : `${adminUiPrefix}/login`;
  if (!token) return <Navigate to={loginTo} replace />;

  return (
    <div className="min-h-full bg-ark-bg">
      <div className="border-b border-ark-line">
        <div className="mx-auto max-w-6xl px-4 py-3 flex items-center justify-between gap-3">
          <div className="flex items-center gap-4">
            {mode === "absolute" ? (
              <Link
                to="/"
                className="text-sm text-neutral-400 hover:text-white"
              >
                ← {t("home")}
              </Link>
            ) : null}
            <NavLink
              to={mode === "basename" ? "." : adminUiPrefix}
              end
              className={({ isActive }) =>
                `text-sm ${isActive ? "text-ark-gold2" : "text-neutral-300 hover:text-white"}`
              }
            >
              {t("dashboard")}
            </NavLink>
            <NavLink
              to={
                mode === "basename" ? "resources" : `${adminUiPrefix}/resources`
              }
              className={({ isActive }) =>
                `text-sm ${isActive ? "text-ark-gold2" : "text-neutral-300 hover:text-white"}`
              }
            >
              {t("resources")}
            </NavLink>
            <NavLink
              to={
                mode === "basename"
                  ? "search-logs"
                  : `${adminUiPrefix}/search-logs`
              }
              className={({ isActive }) =>
                `text-sm ${isActive ? "text-ark-gold2" : "text-neutral-300 hover:text-white"}`
              }
            >
              {t("adminSearchLogs")}
            </NavLink>
          </div>
          <button
            type="button"
            className="text-sm text-neutral-400 hover:text-white"
            onClick={() => {
              clearToken();
              if (mode === "basename") {
                nav("login", { replace: true });
              } else {
                window.location.href = `${adminUiPrefix}/login`;
              }
            }}
          >
            {t("logout")}
          </button>
        </div>
      </div>
      <div className="mx-auto max-w-6xl px-4 py-6">
        <Outlet />
      </div>
    </div>
  );
}
