import { Snackbar } from '@mui/material';
import { useSuspenseQuery } from '@tanstack/react-query';
import { createFileRoute, redirect } from '@tanstack/react-router';
import { t } from 'i18next';
import { useApi } from '../../api/Api';
import { ERRORS } from '../../components/Error/Errors';
import HeaderLayout from '../../components/Layouts/HeaderLayout';
import Profile from '../../components/Profile/Profile';
import { profileSelfQueryOptions } from '../../queries/profileQuery';
import { PostAuth } from '../../types/Post';
import { ROUTES } from '../../types/Routes';

const ProfilePage = () => {
  const Api = useApi();
  const {
    data: { user, posts },
    isFetching,
    error,
    failureReason,
  } = useSuspenseQuery(profileSelfQueryOptions(Api));

  if (failureReason && 'code' in failureReason && failureReason.code === ERRORS.UNAUTHORIZED) {
    throw failureReason;
  }
  if (error && 'code' in error && error.code === ERRORS.UNAUTHORIZED) {
    throw error;
  }

  return (
    <HeaderLayout>
      <Snackbar open={isFetching} message={t('Updating')} />
      <Profile user={user} posts={posts.data as PostAuth[]} canEdit={true} />
    </HeaderLayout>
  );
};

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