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 { formatPrice } from '../utils/formatPrice.ts';
import { usePageTitle } from '../../../shared/hooks/usePageTitle.ts';

const ServicesListComponent: React.FC = () => {
  usePageTitle('Услуги');
  const { services } = useStore();
  const [page, setPage] = useState(1);
  const pageSize = 12;

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

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

  const items = useMemo(
    () => services.list.slice().sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()),
    [services.list],
  );

  const hasItems = items.length > 0;
  const totalPages =
    services.limit && services.total ? Math.ceil(services.total / services.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>
            {services.isLoading && (
              <Typography sx={{ textAlign: 'center' }} color="text.secondary">
                Загружаем услуги...
              </Typography>
            )}
            {services.error && (
              <Typography sx={{ textAlign: 'center' }} color="error">
                {services.error}
              </Typography>
            )}
            {!services.isLoading && !services.error && !hasItems && (
              <Typography sx={{ textAlign: 'center' }} color="text.secondary">
                Услуги пока не добавлены.
              </Typography>
            )}
            {hasItems && (
              <Grid container spacing={2}>
                {items.map((service) => (
                  <Grid key={service.id} size={{ xs: 12, md: 6, lg: 6 }}>
                    <Card sx={{ height: '100%', display: 'flex', flexDirection: 'column' }} variant="outlined">
                      {service.imageUrl ? (
                        <CardMedia component="img" image={service.imageUrl} alt={service.title} sx={{ maxHeight: 220, objectFit: 'cover' }} />
                      ) : null}
                      <CardHeader title={service.title} subheader={service.category?.name ?? 'Без категории'} />
                      <CardContent sx={{ flexGrow: 1, display: 'flex', flexDirection: 'column', gap: 1 }}>
                        <Typography variant="body2" color="text.secondary">
                          {service.description}
                        </Typography>
                        <Typography variant="subtitle2">{formatPrice(service.priceFrom)}</Typography>
                        <Link href={service.href} sx={{ mt: 'auto', alignSelf: 'flex-start' }}>
                          Подробнее
                        </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 ServicesListPage = observer(ServicesListComponent);
