import React, { useEffect } from 'react';

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

import { useStore } from '../../../shared/hooks/useStore.ts';
import { formatPrice } from '../../services/utils/formatPrice.ts';

const ServicesComponent: React.FC = () => {
  const { services } = useStore();

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

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

  const visibleServices = services.list
    .slice()
    .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
    .slice(0, 3);

  const hasServices = visibleServices.length > 0;

  return (
    <Container maxWidth="lg">
      <Box sx={{ display: 'flex', width: '100%' }}>
        <Stack direction="column" spacing={2} sx={{ width: '100%' }}>
          <Typography id="services_anchor" component="h2" variant="h2" gutterBottom sx={{ color: 'text.primary', textAlign: 'center' }}>
            Наши услуги
          </Typography>
          {services.isLoading && (
            <Typography sx={{ textAlign: 'center' }} color="text.secondary">
              Загружаем услуги...
            </Typography>
          )}
          {services.error && (
            <Typography sx={{ textAlign: 'center' }} color="error">
              {services.error}
            </Typography>
          )}
          {hasServices && (
            <Grid container spacing={2}>
              {visibleServices.map((service) => (
                <Grid key={service.id} size={{ xs: 12, md: 6, lg: 4 }}>
                  <Card
                    variant="outlined"
                    sx={{
                      height: '100%',
                      display: 'flex',
                      flexDirection: 'column',
                      justifyContent: 'space-between',
                    }}
                  >
                    <CardHeader title={service.title} subheader={service.category?.name ?? 'Без категории'} sx={{ pb: 0 }} />
                    <CardContent>
                      <Typography variant="caption" color="text.secondary" display="block" sx={{ mb: 1 }}>
                        {formatPrice(service.priceFrom)}
                      </Typography>
                      <Typography gutterBottom color="text.secondary">
                        {service.description}
                      </Typography>
                      <Link href={service.href}>Подробнее</Link>
                    </CardContent>
                  </Card>
                </Grid>
              ))}
            </Grid>
          )}
          {!services.isLoading && !services.error && !hasServices && (
            <Typography sx={{ textAlign: 'center' }} color="text.secondary">
              Услуги скоро появятся.
            </Typography>
          )}
          <Link href={'/services'} sx={{ alignSelf: 'center' }}>
            Все услуги
          </Link>
        </Stack>
      </Box>
    </Container>
  );
};

export const Services = observer(ServicesComponent);
