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

const Home = () => {
  const Api = useApi();
  const { page } = Route.useSearch();
  const { data: postsQuery, isFetching } = useSuspenseQuery(postsQueryOptions(Api, page));
  const { t } = useTranslation();
  const navigate = useNavigate();
  const theme = useTheme();
  const oneSibling = useMediaQuery(theme.breakpoints.not('xs'), { noSsr: true });

  useEffect(() => {
    if ((page ?? 0) >= postsQuery.pages) {
      navigate({ to: '/', search: { page: postsQuery.pages - 1 } });
    }
  }, [page]); //eslint-disable-line react-hooks/exhaustive-deps

  return (
    <HeaderLayout>
      <Snackbar open={isFetching} message={t('Updating')} />
      <Grid container spacing={2} sx={{ marginTop: 0 }}>
        {postsQuery.data.map((post) => (
          <Grid item xs={12} key={post.id}>
            <Post page={page} post={post} />
          </Grid>
        ))}
        <Grid item xs={12}>
          <Divider variant="middle" />
        </Grid>
        <Grid item xs={12} sx={{ display: 'flex', justifyContent: 'center' }}>
          <Pagination
            page={(page ?? 0) + 1}
            count={postsQuery.pages}
            siblingCount={oneSibling ? 1 : 0}
            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>
        {Api.hasAuth ? (
          <Grid item xs={12}>
            <PostForm />
          </Grid>
        ) : (
          <Grid item xs={12}>
            <Typography variant="h5">{t('Leave comment header')}</Typography>
            <Typography>{t('Leave comment action')}</Typography>
          </Grid>
        )}
      </Grid>
    </HeaderLayout>
  );
};

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