import { useEffect } from 'react';

import Alert from '@mui/material/Alert';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import CircularProgress from '@mui/material/CircularProgress';
import IconButton from '@mui/material/IconButton';
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';

const AdminDashboardServiceCategoriesComponent: React.FC = () => {
  const { adminServiceCategories } = useStore();
  const navigate = useNavigate();

  useEffect(() => {
    if (!adminServiceCategories.isLoading && adminServiceCategories.isEmpty) {
      void adminServiceCategories.fetch();
    }
  }, [adminServiceCategories]);

  const sortedCategories = adminServiceCategories.list.slice().sort((a, b) => a.name.localeCompare(b.name, 'ru'));

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

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

  const handleDelete = (id: string) => {
    console.info('Delete category 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>

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

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

      {!adminServiceCategories.isLoading && !adminServiceCategories.error && sortedCategories.length === 0 && (
        <Typography color="text.secondary" textAlign="center">
          Категории пока не добавлены.
        </Typography>
      )}

      {!adminServiceCategories.isLoading && !adminServiceCategories.error && sortedCategories.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 }}>Slug</TableCell>
              <TableCell align="left" sx={{ fontWeight: 600 }}>
                Действия
              </TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {sortedCategories.map((category) => (
              <TableRow key={category.id} hover sx={{ '& td': { borderBottom: '1px solid', borderColor: 'divider' } }}>
                <TableCell>
                  <Typography fontWeight={600}>{category.name}</Typography>
                </TableCell>
                <TableCell>
                  <Typography variant="body2" color="text.secondary">
                    {category.slug}
                  </Typography>
                </TableCell>
                <TableCell align="left">
                  <Tooltip title="Редактировать" sx={{ mr: 1 }}>
                    <IconButton size="small" onClick={() => handleEdit(category.id)}>
                      <EditIcon fontSize="small" />
                    </IconButton>
                  </Tooltip>
                  <Tooltip title="Удалить">
                    <IconButton size="small" color="error" onClick={() => handleDelete(category.id)}>
                      <DeleteIcon fontSize="small" />
                    </IconButton>
                  </Tooltip>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      )}
    </Stack>
  );
};

export const AdminDashboardServiceCategories = observer(AdminDashboardServiceCategoriesComponent);
