import { Fragment, useEffect, useMemo, useState } from 'react';

import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import CardHeader from '@mui/material/CardHeader';
import CardMedia from '@mui/material/CardMedia';
import Container from '@mui/material/Container';
import Grid from '@mui/material/Grid';
import Link from '@mui/material/Link';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import Pagination from '@mui/material/Pagination';
import { observer } from 'mobx-react-lite';

import { Header } from '../../../shared/components/header.tsx';
import { Footer } from '../../../shared/components/footer.tsx';
import { useStore } from '../../../shared/hooks/useStore.ts';
import { formatDate, getDateValue } from '../utils/formatDate.ts';
import { usePageTitle } from '../../../shared/hooks/usePageTitle.ts';

const NewsFeedComponent: React.FC = () => {
  const { news } = useStore();
  const [page, setPage] = useState(1);
  const pageSize = 12;

  useEffect(() => {
    const load = async () => {
      try {
        await news.fetch({ limit: pageSize, page });
      } catch {
        /* handled via store state */
      }
    };

    void load();
  }, [news, page]);

  usePageTitle('Новости');

  const items = useMemo(
    () => news.list.slice().sort((a, b) => getDateValue(b.publishedAt) - getDateValue(a.publishedAt)),
    [news.list],
  );

  const hasItems = items.length > 0;
  const totalPages =
    news.limit && news.total ? Math.ceil(news.total / news.limit) : hasItems ? Math.max(page, 1) : 0;

  useEffect(() => {
    if (totalPages > 0 && page > totalPages) {
      setPage(totalPages);
    }
  }, [page, totalPages]);

  return (
    <Fragment>
      <Header />
      <Box component="main" sx={{ pt: { xs: 12, md: 18 }, pb: 6 }}>
        <Container maxWidth="lg">
          <Stack spacing={3}>
            <Typography variant="h2" component="h1" sx={{ textAlign: 'center' }}>
              Новости
            </Typography>
            {news.isLoading && (
              <Typography sx={{ textAlign: 'center' }} color="text.secondary">
                Загружаем новости...
              </Typography>
            )}
            {news.error && (
              <Typography sx={{ textAlign: 'center' }} color="error">
                {news.error}
              </Typography>
            )}
            {!news.isLoading && !news.error && !hasItems && (
              <Typography sx={{ textAlign: 'center' }} color="text.secondary">
                Новости пока не опубликованы.
              </Typography>
            )}
            {hasItems && (
              <Grid container spacing={2}>
                {items.map((item) => (
                  <Grid key={item.id} size={12}>
                    <Card variant="outlined" sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
                      {item.imageUrl && (
                        <CardMedia
                          component="img"
                          height="220"
                          image={item.imageUrl}
                          alt={item.title}
                          sx={{ objectFit: 'cover' }}
                        />
                      )}
                      <CardHeader
                        title={item.title}
                        subheader={formatDate(item.publishedAt)}
                        sx={{ pb: 0, '& .MuiCardHeader-title': { fontSize: '1.25rem' } }}
                      />
                      <CardContent sx={{ flexGrow: 1 }}>
                        <Typography paragraph color="text.secondary">
                          {item.summary}
                        </Typography>
                        <Link href={item.href}>Читать полностью</Link>
                      </CardContent>
                    </Card>
                  </Grid>
                ))}
              </Grid>
            )}
            {hasItems && totalPages > 1 && (
              <Pagination
                page={page}
                onChange={(_, value) => setPage(value)}
                count={totalPages}
                color="primary"
                sx={{ alignSelf: 'center' }}
                showFirstButton
                showLastButton
              />
            )}
          </Stack>
        </Container>
      </Box>
      <Footer />
    </Fragment>
  );
};

export const NewsFeedPage = observer(NewsFeedComponent);
