import { isCuid } from "@paralleldrive/cuid2";
import { useSuspenseQuery } from "@tanstack/react-query";
import { createFileRoute, Link } from "@tanstack/react-router";
import { zodValidator } from "@tanstack/zod-adapter";
import { z } from "zod";
import { gameHistoryQueryOptions } from "~/lib/api/game-history";
import { Button } from "~/lib/components/ui/button";

const paramsSchema = z.object({
  providerId: z.array(z.string().refine((id) => isCuid(id), "Invalid cuid")),
  categoryId: z.array(z.number()),
});

export const Route = createFileRoute("/_authed/game-history")({
  validateSearch: zodValidator(paramsSchema),
  loaderDeps: ({ search }) => search,

  beforeLoad: ({ context }) => {
    if (!context.user) {
      throw new Error("Not authenticated");
    }
  },

  component: RouteComponent,
  loader: async ({ context, deps }) => {
    const gameHistory = await context.queryClient.ensureQueryData(
      gameHistoryQueryOptions(deps),
    );

    return { gameHistory };
  },
});

function RouteComponent() {
  const deps = Route.useLoaderDeps();
  console.log("🚀 ~ RouteComponent ~ deps:", deps);

  const gameHistoryQuery = useSuspenseQuery(gameHistoryQueryOptions(deps));

  return (
    <div className="flex flex-col gap-8">
      <Button type="button" asChild className="w-fit" size="lg">
        <Link to="/dashboard">Dashboard</Link>
      </Button>

      <h1>Game History</h1>

      <pre className="rounded-md border bg-card p-1 text-card-foreground">
        {gameHistoryQuery.data?.map((gameHistory) => gameHistory.game.name)}
      </pre>
    </div>
  );
}
