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, profileSelfQueryOptions } from '../../queries/profileQuery';
import { PostAuth } from '../../types/Post';
import { ROUTES } from '../../types/Routes';

const ProfilePage = () => {
  const { data: profileQuery, isFetching: isFetchingProfile } = useSuspenseQuery(profileSelfQueryOptions);
  const { data: profilePostsQuery, isFetching: isFetchingPosts } = useSuspenseQuery(
    profilePostsQueryOptions(Api.getAuthenticatedUser()?.id ?? 0)
  );

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

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