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 { formatDate, getDateValue } from '../../../news/utils/formatDate.ts';

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

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

  const sortedNews = useMemo(
    () => news.list.slice().sort((a, b) => getDateValue(b.publishedAt) - getDateValue(a.publishedAt)),
    [news.list],
  );
  const totalPages =
    news.limit && news.total ? Math.ceil(news.total / news.limit) : sortedNews.length === pageSize ? page + 1 : page;

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

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

  const handleEdit = (slug: string) => {
    if (!slug) {
      return;
    }
    navigate(`/admin/dashboard/news/${slug}/edit`);
  };

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

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

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

      {!news.isLoading && !news.error && sortedNews.length === 0 && (
        <Typography color="text.secondary" textAlign="center">
          Ни одной новости пока не добавлено.
        </Typography>
      )}

      {!news.isLoading && !news.error && sortedNews.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>
            {sortedNews.map((item) => (
              <TableRow key={item.id} hover sx={{ '& td': { borderBottom: '1px solid', borderColor: 'divider' } }}>
                <TableCell sx={{ maxWidth: 220 }}>
                  <Typography fontWeight={600}>{item.title}</Typography>
                  <Typography variant="caption" color="text.secondary">
                    {item.slug}
                  </Typography>
                </TableCell>
                <TableCell sx={{ whiteSpace: 'nowrap' }}>{formatDate(item.publishedAt)}</TableCell>
                <TableCell>
                  <Typography
                    variant="body2"
                    color="text.secondary"
                    sx={{ display: '-webkit-box', overflow: 'hidden', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' }}
                  >
                    {item.summary}
                  </Typography>
                </TableCell>
                <TableCell>
                  <Chip
                    size="small"
                    label={item.status}
                    color={item.status === 'published' ? 'success' : item.status === 'draft' ? 'default' : 'warning'}
                    sx={{ textTransform: 'capitalize' }}
                  />
                </TableCell>
                <TableCell align="left">
                  <Tooltip title="Редактировать" sx={{ mr: 1 }}>
                    <IconButton size="small" onClick={() => handleEdit(item.slug)}>
                      <EditIcon fontSize="small" />
                    </IconButton>
                  </Tooltip>
                  <Tooltip title="Удалить">
                    <IconButton size="small" color="error" onClick={() => handleDelete(item.id)}>
                      <DeleteIcon fontSize="small" />
                    </IconButton>
                  </Tooltip>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      )}
      {!news.isLoading && !news.error && sortedNews.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 AdminDashboardNews = observer(AdminDashboardNewsComponent);
