import { badgeKeys, badgeQueries } from "@/features/badges/queries";
import Profile from "@/features/players/components/profile";
import HeaderSkeleton from "@/features/players/components/profile/header-skeleton";
import ProfileSkeleton from "@/features/players/components/profile/skeleton";
import { playerKeys, playerQueries } from "@/features/players/queries";
import { prefetchServerQuery } from "@/lib/tanstack-query/utils/prefetch";
import { createFileRoute } from "@tanstack/react-router";
import { Suspense } from "react";
import { z } from "zod";

const searchSchema = z.object({
  tab: z.string().optional(),
});

export const Route = createFileRoute("/_authed/profile/$playerId")({
  validateSearch: searchSchema,
  beforeLoad: async ({ params, context }) => {
    const { queryClient } = context;
    await Promise.all([
      prefetchServerQuery(
        queryClient,
        playerQueries.details(params.playerId)
      ),
      prefetchServerQuery(
        queryClient,
        playerQueries.matches(params.playerId)
      ),
      prefetchServerQuery(
        queryClient,
        playerQueries.stats(params.playerId)
      ),
      prefetchServerQuery(
        queryClient,
        badgeQueries.playerBadges(params.playerId)
      ),
    ]);
  },
  loader: ({ params, context }) => ({
    header: {
      collapsed: true,
      withBackButton: true,
      settingsLink:
        context?.auth.user.id === params.playerId ? "/settings" : undefined,
    },
    withPadding: false,
    refresh: [playerKeys.details(params.playerId), playerKeys.matches(params.playerId), playerKeys.stats(params.playerId), badgeKeys.playerBadges(params.playerId)],
  }),
  component: () => {
    const { playerId } = Route.useParams();
    return <Suspense fallback={<ProfileSkeleton />}>
       <Profile id={playerId} />
    </Suspense>;
  },
});
