import { Fragment, useEffect } from 'react';

import Box from '@mui/material/Box';
import Breadcrumbs from '@mui/material/Breadcrumbs';
import Container from '@mui/material/Container';
import Link from '@mui/material/Link';
import Skeleton from '@mui/material/Skeleton';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { observer } from 'mobx-react-lite';
import { useParams } from 'react-router';

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

const NewsDetailsComponent: React.FC = () => {
  const { slug } = useParams<{ slug: string }>();
  const { news } = useStore();

  const currentNews = slug ? news.getBySlug(slug) : undefined;

  useEffect(() => {
    if (!slug || currentNews) {
      return;
    }

    const load = async () => {
      try {
        await news.fetchBySlug(slug);
      } catch {
        /* handled via store state */
      }
    };

    void load();
  }, [currentNews, news, slug]);

  const resolvedNews = currentNews ?? (slug ? news.getBySlug(slug) : undefined);
  const isLoading = news.isLoading && !resolvedNews;
  const showError = news.error && !resolvedNews;
  usePageTitle(resolvedNews?.title ? `Новость: ${resolvedNews.title}` : 'Новость');

  return (
    <Fragment>
      <Header />
      <Box component="main" sx={{ pt: { xs: 12, md: 18 }, pb: 6 }}>
        <Container maxWidth="md">
          <Stack spacing={3}>
            <Breadcrumbs aria-label="breadcrumbs">
              <Link underline="hover" color="inherit" href="/">
                Главная
              </Link>
              <Link underline="hover" color="inherit" href="/news">
                Новости
              </Link>
              <Typography color="text.primary">{resolvedNews?.title ?? 'Загрузка...'}</Typography>
            </Breadcrumbs>
            {isLoading && (
              <Stack spacing={2}>
                <Skeleton variant="text" height={60} />
                <Skeleton variant="rectangular" height={200} />
                <Skeleton variant="text" height={40} />
              </Stack>
            )}
            {showError && (
              <Typography color="error" sx={{ textAlign: 'center' }}>
                {news.error}
              </Typography>
            )}
            {!isLoading && !showError && resolvedNews && (
              <Stack spacing={2}>
                <Typography variant="h3" component="h1">
                  {resolvedNews.title}
                </Typography>
                <Typography variant="subtitle2" color="text.secondary">
                  {formatDate(resolvedNews.publishedAt)}
                </Typography>
                {resolvedNews.imageUrl ? (
                  <Box
                    component="img"
                    src={resolvedNews.imageUrl}
                    alt={resolvedNews.title}
                    sx={{ width: '100%', borderRadius: 2, objectFit: 'cover', maxHeight: { xs: 260, md: 420 } }}
                  />
                ) : null}
                <Typography variant="body1">{resolvedNews.summary}</Typography>
                {resolvedNews.content && (
                  <Typography variant="body1" sx={{ whiteSpace: 'pre-line' }}>
                    {resolvedNews.content}
                  </Typography>
                )}
              </Stack>
            )}
            {!isLoading && !showError && !resolvedNews && (
              <Typography sx={{ textAlign: 'center' }} color="text.secondary">
                Новость не найдена или была удалена.
              </Typography>
            )}
          </Stack>
        </Container>
      </Box>
      <Footer />
    </Fragment>
  );
};

export const NewsDetailsPage = observer(NewsDetailsComponent);
