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

const ProfilePage = () => {
  const Api = useApi();
  const { id } = Route.useParams();
  const {
    data: { user, posts },
    isFetching,
    error,
    failureReason,
  } = useSuspenseQuery(profileQueryOptions(Api, id));

  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={Api.authenticatedUser?.isAdmin} />
    </HeaderLayout>
  );
};

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