import { Snackbar } from '@mui/material';
import { queryOptions, 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 { ROUTES } from '../../types/Routes';

const profileQueryOptions = (id?: number) =>
  queryOptions({
    queryKey: ['profile', { id }],
    queryFn: () => Api.user(id),
  });

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

  return (
    <>
      <Snackbar open={isFetching} message={t('Updating')} />
      <Profile user={profileQuery} 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)),
  beforeLoad: ({ params: { id } }) => {
    if (!Api.hasAuth()) throw redirect({ to: ROUTES.INDEX });
    if (id === Api.getAuthenticatedUser()?.id) throw redirect({ to: ROUTES.PROFILE });
  },
  component: ProfilePage,
});
