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

import Alert from '@mui/material/Alert';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Chip from '@mui/material/Chip';
import CircularProgress from '@mui/material/CircularProgress';
import IconButton from '@mui/material/IconButton';
import Pagination from '@mui/material/Pagination';
import Stack from '@mui/material/Stack';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Tooltip from '@mui/material/Tooltip';
import Typography from '@mui/material/Typography';
import EditIcon from '@mui/icons-material/EditRounded';
import DeleteIcon from '@mui/icons-material/DeleteRounded';
import { observer } from 'mobx-react-lite';
import { useNavigate } from 'react-router-dom';

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

const AdminDashboardServicesComponent: React.FC = () => {
  const { services } = useStore();
  const navigate = useNavigate();
  const [page, setPage] = useState(1);
  const pageSize = 10;

  useEffect(() => {
    void services.fetchAdmin({ limit: pageSize, page }, { replace: true });
  }, [services, page]);

  const sortedServices = useMemo(
    () => services.list.slice().sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()),
    [services.list],
  );
  const totalPages =
    services.limit && services.total
      ? Math.ceil(services.total / services.limit)
      : sortedServices.length === pageSize
        ? page + 1
        : page;

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

  const handleAdd = () => {
    navigate('/admin/dashboard/services/new');
  };

  const handleEdit = (id: string) => {
    navigate(`/admin/dashboard/services/${id}/edit`);
  };

  const handleDelete = (id: string) => {
    console.info('Delete service action is not implemented yet', id);
  };

  return (
    <Stack spacing={3}>
      <Stack direction={{ xs: 'column', sm: 'row' }} justifyContent="space-between" alignItems={{ xs: 'stretch', sm: 'center' }} spacing={2}>
        <div>
          <Typography variant="h5">Услуги</Typography>
          <Typography color="text.secondary">Добавляйте новые услуги, обновляйте цены и статусы.</Typography>
        </div>
        <Button onClick={handleAdd} variant="contained" size="small">
          Добавить услугу
        </Button>
      </Stack>

      {services.isLoading && (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
          <CircularProgress size={28} />
        </Box>
      )}

      {services.error && <Alert severity="error">{services.error}</Alert>}

      {!services.isLoading && !services.error && sortedServices.length === 0 && (
        <Typography color="text.secondary" textAlign="center">
          Услуги пока не добавлены.
        </Typography>
      )}

      {!services.isLoading && !services.error && sortedServices.length > 0 && (
        <Table
          size="small"
          sx={{
            border: 1,
            borderColor: 'divider',
            borderRadius: 1,
            overflow: 'hidden',
            '& th, & td': {
              borderRight: '1px solid',
              borderColor: 'divider',
              '&:last-of-type': {
                borderRight: 'none',
              },
            },
          }}
        >
          <TableHead>
            <TableRow sx={{ backgroundColor: 'action.hover' }}>
              <TableCell sx={{ fontWeight: 600 }}>Название</TableCell>
              <TableCell sx={{ fontWeight: 600 }}>Категория</TableCell>
              <TableCell sx={{ fontWeight: 600 }}>Стоимость</TableCell>
              <TableCell sx={{ fontWeight: 600 }}>Статус</TableCell>
              <TableCell align="left" sx={{ fontWeight: 600 }}>
                Действия
              </TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {sortedServices.map((service) => (
              <TableRow key={service.id} hover sx={{ '& td': { borderBottom: '1px solid', borderColor: 'divider' } }}>
                <TableCell sx={{ maxWidth: 220 }}>
                  <Typography fontWeight={600}>{service.title}</Typography>
                  <Typography variant="caption" color="text.secondary">
                    {service.slug || service.id}
                  </Typography>
                </TableCell>
                <TableCell>{service.category?.name ?? 'Без категории'}</TableCell>
                <TableCell>{formatPrice(service.priceFrom)}</TableCell>
                <TableCell>
                  <Chip
                    size="small"
                    label={service.status || '—'}
                    color={service.status?.toUpperCase() === 'PUBLISHED' ? 'success' : 'default'}
                  />
                </TableCell>
                <TableCell align="left">
                  <Tooltip title="Редактировать" sx={{ mr: 1 }}>
                    <IconButton size="small" onClick={() => handleEdit(service.id)}>
                      <EditIcon fontSize="small" />
                    </IconButton>
                  </Tooltip>
                  <Tooltip title="Удалить">
                    <IconButton size="small" color="error" onClick={() => handleDelete(service.id)}>
                      <DeleteIcon fontSize="small" />
                    </IconButton>
                  </Tooltip>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      )}
      {!services.isLoading && !services.error && sortedServices.length > 0 && totalPages > 1 && (
        <Box sx={{ display: 'flex', justifyContent: 'center' }}>
          <Pagination
            page={page}
            onChange={(_, value) => setPage(value)}
            count={totalPages}
            color="primary"
            showFirstButton
            showLastButton
          />
        </Box>
      )}
    </Stack>
  );
};

export const AdminDashboardServices = observer(AdminDashboardServicesComponent);
