import { createFileRoute, redirect } from "@tanstack/react-router";
import { tournamentQueries, useTournament } from "@/features/tournaments/queries";
import { predictionQueries, useMyPrediction } from "@/features/predictions/queries";
import { ensureServerQueryData } from "@/lib/tanstack-query/utils/ensure";
import { Container } from "@mantine/core";
import { BracketPending } from "@/features/bracket/components/bracket-pending";
import { PredictionEditor } from "@/features/predictions/components/prediction-editor";

export const Route = createFileRoute(
  "/_authed/tournaments/$id/predictions_/make"
)({
  beforeLoad: async ({ context, params }) => {
    const { queryClient } = context;
    const tournament = await ensureServerQueryData(
      queryClient,
      tournamentQueries.details(params.id)
    );
    if (!tournament) throw redirect({ to: "/tournaments" });

    const myPrediction = await ensureServerQueryData(
      queryClient,
      predictionQueries.mine(params.id)
    );
    if (!myPrediction.eligible || myPrediction.locked) {
      throw redirect({
        to: "/tournaments/$id/predictions",
        params: { id: params.id },
      });
    }

    return {
      tournament,
    };
  },
  loader: ({ context }) => ({
    fullWidth: true,
    withPadding: false,
    header: {
      withBackButton: true,
      title: `${context.tournament.name}`,
    },
  }),
  component: RouteComponent,
  pendingComponent: BracketPending,
});

function RouteComponent() {
  const { id } = Route.useParams();
  const { data: tournament } = useTournament(id);
  const { data: myPrediction } = useMyPrediction(id);

  return (
    <Container size="md" px={0}>
      <PredictionEditor
        tournament={tournament}
        initialPicks={myPrediction.prediction?.picks ?? {}}
      />
    </Container>
  );
}
