import { Divider, Grid, Pagination, PaginationItem, Snackbar } from '@mui/material';
import { useSuspenseQuery } from '@tanstack/react-query';
import { createFileRoute, Link } from '@tanstack/react-router';
import { useTranslation } from 'react-i18next';
import Api from '../api/Api';
import PostForm from '../components/Forms/Post/PostForm';
import Post from '../components/Post/Post';
import { postsQueryOptions } from '../queries/postsQuery';
import { ROUTES } from '../types/Routes';

const Home = () => {
  const { page } = Route.useSearch();
  const { data: postsQuery, isFetching } = useSuspenseQuery(postsQueryOptions(page));
  const { t } = useTranslation();

  return (
    <>
      <Snackbar open={isFetching} message={t('Updating')} />
      <Grid container spacing={2}>
        {postsQuery.data.map((post) => (
          <Grid item xs={12} key={post.id}>
            <Post post={post} />
          </Grid>
        ))}
        <Grid item xs={12}>
          <Divider variant="middle" />
        </Grid>
        {Api.hasAuth() && (
          <Grid item xs={12}>
            <PostForm />
          </Grid>
        )}
        <Grid item xs={12} sx={{ display: 'flex', justifyContent: 'center' }}>
          <Pagination
            page={(page ?? 0) + 1}
            count={postsQuery.pages}
            color="primary"
            renderItem={(item) => (
              <PaginationItem
                {...item}
                component={Link}
                to="/"
                search={{ page: (item.page ?? 0) > 0 ? (item.page ?? 1) - 1 : undefined }}
                //eslint-disable-next-line @typescript-eslint/no-explicit-any
                onClick={(e) => item.onClick(e as any)}
              />
            )}
          />
        </Grid>
      </Grid>
    </>
  );
};

export const Route = createFileRoute(ROUTES.INDEX)({
  loaderDeps: ({ search: { page } }) => ({ page }),
  loader: ({ context: { queryClient }, deps: { page } }) => queryClient.ensureQueryData(postsQueryOptions(page)),
  validateSearch: (search: Record<string, unknown>): { page?: number } => {
    return {
      page: search?.page !== undefined ? Number(search?.page ?? 0) : undefined,
    };
  },
  component: Home,
});
