"use client";

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import { AdminConsole } from "@/components/admin-console";

export function ManageConsoleShell() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [client] = useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            refetchOnWindowFocus: false,
            retry: 1,
            staleTime: 20_000,
          },
        },
      })
  );
  const [ready, setReady] = useState(false);
  const [platformKey, setPlatformKey] = useState("");

  useEffect(() => {
    const key = searchParams.get("platformKey")?.trim() || "";
    if (key) {
      setPlatformKey(key);
      const url = new URL(window.location.href);
      url.searchParams.delete("platformKey");
      router.replace(url.pathname + url.search + url.hash);
      setReady(true);
      return;
    }
    if (!platformKey.trim()) {
      router.replace("/login");
      return;
    }
    setReady(true);
  }, [platformKey, router, searchParams]);

  if (!ready) {
    return (
      <main className="grid min-h-screen place-items-center bg-[radial-gradient(circle_at_top_left,rgba(240,253,244,0.95),rgba(255,255,255,0.96)_34%,rgba(239,246,255,0.98)_100%)] px-4 py-8">
        <div className="w-full max-w-md rounded-xl border border-slate-200/80 bg-white/90 p-6 text-center shadow-soft">
          <div className="mx-auto mb-4 h-3 w-24 rounded-full bg-slate-200" />
          <p className="text-sm font-black uppercase tracking-[0.14em] text-slate-500">Admin console</p>
          <h1 className="mt-2 text-2xl font-black text-slate-950">Loading admin console...</h1>
          <p className="mt-2 text-sm leading-6 text-slate-600">Checking the current session and preparing the operator dashboard.</p>
        </div>
      </main>
    );
  }

  return (
    <QueryClientProvider client={client}>
      <AdminConsole initialAdminKey={platformKey} />
    </QueryClientProvider>
  );
}
