import { Fragment, useEffect } from 'react';

import Box from '@mui/material/Box';
import Breadcrumbs from '@mui/material/Breadcrumbs';
import CardMedia from '@mui/material/CardMedia';
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 { formatPrice } from '../utils/formatPrice.ts';
import { formatDate } from '../../news/utils/formatDate.ts';
import { usePageTitle } from '../../../shared/hooks/usePageTitle.ts';

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

  const resolveService = () => {
    if (!slug) {
      return undefined;
    }
    return services.getBySlug(slug) ?? services.getById(slug);
  };

  const service = resolveService();

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

    const load = async () => {
      try {
        await services.fetchBySlug(slug);
      } catch {
        /* handled via store */
      }
    };
    void load();
  }, [service, services, slug]);

  const resolved = service ?? resolveService();
  usePageTitle(resolved?.title ? `Услуга: ${resolved.title}` : 'Услуга');
  const isLoading = services.isLoading && !resolved;
  const showError = services.error && !resolved;

  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="/services">
                Услуги
              </Link>
              <Typography color="text.primary">{resolved?.title ?? 'Загрузка...'}</Typography>
            </Breadcrumbs>
            {isLoading && (
              <Stack spacing={2}>
                <Skeleton variant="text" height={60} />
                <Skeleton variant="rectangular" height={200} />
                <Skeleton variant="text" height={80} />
              </Stack>
            )}
            {showError && (
              <Typography color="error" sx={{ textAlign: 'center' }}>
                {services.error}
              </Typography>
            )}
            {!isLoading && !showError && resolved && (
              <Stack spacing={3}>
                <Typography variant="h3" component="h1">
                  {resolved.title}
                </Typography>
                {resolved.imageUrl ? (
                  <CardMedia
                    component="img"
                    image={resolved.imageUrl}
                    alt={resolved.title}
                    sx={{ borderRadius: 2, maxHeight: 360, objectFit: 'cover' }}
                  />
                ) : null}
                <Stack spacing={1}>
                  <Typography variant="subtitle1">{resolved.category?.name ?? 'Без категории'}</Typography>
                  <Typography variant="subtitle1">Стоимость: {formatPrice(resolved.priceFrom)}</Typography>
                  <Typography variant="body2" color="text.secondary">
                    Обновлено: {formatDate(resolved.updatedAt)} | Создано: {formatDate(resolved.createdAt)}
                  </Typography>
                </Stack>
                <Typography variant="body1">{resolved.description}</Typography>
                <Link href="/services" underline="hover">
                  Вернуться к списку услуг
                </Link>
              </Stack>
            )}
            {!isLoading && !showError && !resolved && (
              <Typography sx={{ textAlign: 'center' }} color="text.secondary">
                Услуга не найдена или была удалена.
              </Typography>
            )}
          </Stack>
        </Container>
      </Box>
      <Footer />
    </Fragment>
  );
};

export const ServiceDetailsPage = observer(ServiceDetailsComponent);
