import { Snackbar } from '@mui/material';
import { useSuspenseQuery } from '@tanstack/react-query';
import { createFileRoute, redirect } from '@tanstack/react-router';
import { t } from 'i18next';
import Api from '../../api/Api';
import Profile from '../../components/Profile/Profile';
import { profilePostsQueryOptions, profileQueryOptions } from '../../queries/profileQuery';
import { PostAuth } from '../../types/Post';
import { ROUTES } from '../../types/Routes';

const ProfilePage = () => {
  const { id } = Route.useParams();
  const { data: profileQuery, isFetching: isFetchingProfile } = useSuspenseQuery(profileQueryOptions(id));
  const { data: profilePostsQuery, isFetching: isFetchingPosts } = useSuspenseQuery(profilePostsQueryOptions(id));

  return (
    <>
      <Snackbar open={isFetchingProfile || isFetchingPosts} message={t('Updating')} />
      <Profile user={profileQuery} posts={profilePostsQuery.data as PostAuth[]} canEdit={Api.isAdmin()} />
    </>
  );
};

export const Route = createFileRoute(`${ROUTES.PROFILE}/$id`)({
  params: {
    parse: ({ id }) => ({ id: parseInt(id) }),
    stringify: ({ id }) => ({ id: id.toString() }),
  },
  loader: ({ context: { queryClient }, params: { id } }) => {
    queryClient.ensureQueryData(profileQueryOptions(id));
    queryClient.ensureQueryData(profilePostsQueryOptions(id));
  },
  beforeLoad: ({ params: { id } }) => {
    if (!Api.hasAuth()) throw redirect({ to: ROUTES.INDEX });
    if (id === Api.getAuthenticatedUser()?.id) throw redirect({ to: ROUTES.PROFILE });
  },
  component: ProfilePage,
});
