import { useState } from 'react';
import {
  TableBody,
  TableCell,
  TableRow,
  Typography,
  IconButton,
  Menu,
  MenuItem,
  Divider,
} from '@mui/material';
import MoreVertIcon from '@mui/icons-material/MoreVert';
import {
  StyledTable,
  StyledTableContainer,
  StyledTableHead,
  StyledTableHeadRow,
  StyledTableRow,
} from './StagesTable.style';
import { getStageStatus, getStatusColors } from './utils';
import { formatDate } from '../../../utils/formatDate';
import { StageStatusChip } from '../StageStatusChip';
import { ROLES_NAME_ID, SHEET_NAME, STAGE_ROLE_RUSSIAN_NAME } from '../../../constants/constants';
import { useAuth } from '../../../app/context/AuthProvider';

export const StagesTable = ({ stages, onEdit, onDelete }) => {
  const [anchorEl, setAnchorEl] = useState(null);
  const [selectedStage, setSelectedStage] = useState(null);
  const { user } = useAuth();
  const isAdmin = user?.role_id === ROLES_NAME_ID.admin;

  const handleOpenMenu = (event, stage) => {
    setAnchorEl(event.currentTarget);
    setSelectedStage(stage);
  };

  const handleCloseMenu = () => {
    setAnchorEl(null);
    setSelectedStage(null);
  };

  const handleEdit = () => {
    if (selectedStage) {
      onEdit(selectedStage);
      handleCloseMenu();
    }
  };

  const handleDelete = () => {
    if (selectedStage) {
      onDelete(selectedStage);
      handleCloseMenu();
    }
  };

  return (
    <>
      <Divider />
      <StyledTableContainer>
        <StyledTable>
          <StyledTableHead>
            <StyledTableHeadRow>
              <TableCell>Название таблицы</TableCell>
              <TableCell>Начало</TableCell>
              <TableCell>Окончание</TableCell>
              <TableCell>Статус</TableCell>
              <TableCell align="right"></TableCell>
            </StyledTableHeadRow>
          </StyledTableHead>
          <TableBody>
            {!stages || stages.length === 0 ? (
              <TableRow>
                <TableCell colSpan={5} align="center">
                  <Typography variant="body2">
                    {' '}
                    Нет данных для отображения
                  </Typography>
                </TableCell>
              </TableRow>
            ) : (
              stages.map((stage, index) => {
                const status = getStageStatus(stage);
                const colors = getStatusColors(status);
                const rowKey = `${stage.sheet}-${stage.phase_code}-${stage.role}-${index}`;
                return (
                  <StyledTableRow key={rowKey}>
                    <TableCell>
                      <Typography variant="body2">{SHEET_NAME[stage.sheet]} - {stage.phase_code}</Typography>
                      <Typography
                        variant="caption"
                        color="text.secondary"
                        sx={{ fontSize: '0.65rem' }}
                      >
                        {STAGE_ROLE_RUSSIAN_NAME[stage.role] ?? stage.role}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2">
                        {formatDate(stage.opens_at)}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2">
                        {formatDate(stage.closes_at)}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <StageStatusChip
                        label={status}
                        bg={colors.bg}
                        color={colors.color}
                        border={colors.border}
                      />
                    </TableCell>
                    <TableCell align="right">
                      {isAdmin && (
                        <IconButton
                          size="small"
                          onClick={(e) => handleOpenMenu(e, stage)}
                        >
                          <MoreVertIcon />
                        </IconButton>
                      )}
                    </TableCell>
                  </StyledTableRow>
                );
              })
            )}
          </TableBody>
        </StyledTable>
      </StyledTableContainer>

      {isAdmin && (
        <Menu
          anchorEl={anchorEl}
          open={Boolean(anchorEl)}
          onClose={handleCloseMenu}
          anchorOrigin={{
            vertical: 'bottom',
            horizontal: 'right',
          }}
          transformOrigin={{
            vertical: 'top',
            horizontal: 'right',
          }}
        >
          <MenuItem onClick={handleEdit}>Редактировать</MenuItem>
          {onDelete && (
            <MenuItem onClick={handleDelete} sx={{ color: 'rgb(194, 78, 33)' }}>
              Удалить
            </MenuItem>
          )}
        </Menu>
      )}
    </>
  );
};
