import { useEffect } from "react";
import { redirect, useFetcher } from "react-router";
import { Loader2 } from "lucide-react";
import { auth } from "~/lib/auth.server";
import { loadWizardState, clearWizardState, buildFormDataFromSnapshot } from "~/lib/wizard-state";
import type { Route } from "./+types/creating";

export async function loader(args: Route.LoaderArgs) {
  const session = await auth.api.getSession({ headers: args.request.headers });
  if (!session?.user) return redirect("/leagues/new");
  return null;
}

export function meta(): Route.MetaDescriptors {
  return [{ title: "Creating League… - Brackt" }];
}

export default function CreatingLeague() {
  const fetcher = useFetcher();

  useEffect(() => {
    const saved = loadWizardState();
    if (!saved) {
      window.location.replace("/leagues/new");
      return;
    }
    fetcher.submit(buildFormDataFromSnapshot(saved), { method: "post", action: "/leagues/new" });
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  // Clear saved state only after a confirmed failure so the user can retry if
  // the server returns an error (a successful submit navigates away immediately).
  useEffect(() => {
    if (fetcher.state === "idle" && fetcher.data !== null && fetcher.data !== undefined) {
      clearWizardState();
    }
  }, [fetcher.state, fetcher.data]);

  const submitError =
    fetcher.data && typeof fetcher.data === "object" && "error" in fetcher.data
      ? String((fetcher.data as { error: unknown }).error)
      : null;

  if (submitError) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="text-center space-y-4 max-w-sm px-4">
          <p className="text-destructive font-medium">{submitError}</p>
          <a href="/leagues/new" className="text-sm underline text-muted-foreground">
            Go back and try again
          </a>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background flex items-center justify-center">
      <div className="text-center space-y-4">
        <Loader2 className="h-10 w-10 animate-spin mx-auto text-primary" />
        <div>
          <p className="text-lg font-semibold">Creating your league…</p>
          <p className="text-sm text-muted-foreground mt-1">Logged in successfully. Just a moment.</p>
        </div>
      </div>
    </div>
  );
}
