import { type MouseEvent, useState } from 'react';
// biome-ignore lint/style/noRestrictedImports: legacy usage, migration pending
import { type DraggableProvided } from 'react-beautiful-dnd';

import DragHandleOutlined from '@material-hu/icons/material/DragHandleOutlined';
import ButtonBase from '@material-hu/mui/ButtonBase';
import Stack, { type StackProps } from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Tooltip from '@material-hu/mui/Tooltip';
import Typography from '@material-hu/mui/Typography';

import IconsMenu from '@material-hu/components/deprecated/IconsMenu';

import { TASKS_ICONS } from 'src/pages/dashboard/Learning/Courses/New/constants';
import {
  getTaskElementId,
  validateTask,
} from 'src/pages/dashboard/Learning/Courses/New/utils';
import { type Task } from 'src/pages/dashboard/Learning/Courses/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

export type TaskListItemProps = StackProps & {
  moduleIndex: number;
  taskIndex: number;
  task: Task;
  onSelect?: (event: MouseEvent<HTMLButtonElement>) => void;
  onDelete?: () => void;
  selected?: boolean;
  draggableProvided: DraggableProvided;
  draggingOver: string;
  hoveredOver: boolean;
};

const tooltipTextStyles = {
  fontFamily: 'Roboto',
  fontSize: '12px',
  fontWeight: 500,
  lineHeight: '14px',
  color: 'white',
};

export const TaskListItem = ({
  moduleIndex,
  taskIndex,
  task,
  onSelect = () => null,
  onDelete = () => null,
  selected = false,
  draggableProvided,
  draggingOver,
  hoveredOver,
  ...stackProps
}: TaskListItemProps) => {
  const [showActions, setShowActions] = useState(false);
  const [openMenu, setOpenMenu] = useState(false);

  const { t } = useLokaliseTranslation('learning');
  const theme = useTheme();

  const handleMouseOver = () => {
    setShowActions(true);
  };

  const handleMouseOut = () => {
    if (!openMenu) {
      setShowActions(false);
    }
  };

  const handleOpenMenu = () => {
    setOpenMenu(true);
  };

  const handleCloseMenu = () => {
    setShowActions(false);
    setOpenMenu(false);
  };

  const options = [
    {
      onClick: onDelete,
      label: t('general:delete'),
      color: theme.palette.error.main,
    },
  ];

  const { Icon, color } = TASKS_ICONS[task.type];

  const isIncomplete = !validateTask(task);
  const tooltipText = isIncomplete ? (
    <>
      <span style={{ ...tooltipTextStyles }}>
        {t('course.lesson.incomplete')}.
      </span>
      <br />
      <span style={{ ...tooltipTextStyles }}>
        {t('course.lesson.no_publish_lesson')}
      </span>
    </>
  ) : (
    ''
  );

  return (
    <Stack
      sx={{ width: '100%' }}
      ref={draggableProvided.innerRef}
      {...draggableProvided.draggableProps}
      {...draggableProvided.dragHandleProps}
      {...stackProps}
    >
      <ButtonBase
        id={getTaskElementId(moduleIndex, taskIndex)}
        component="div"
        role="button"
        onClick={onSelect}
        onMouseOver={handleMouseOver}
        onMouseOut={handleMouseOut}
        disableRipple
        sx={{
          borderBottomLeftRadius: theme.spacing(1),
          borderBottomRightRadius: theme.spacing(1),
          backgroundColor:
            selected || draggingOver
              ? '#F3F4F6'
              : theme.palette.background.paper,
          '&:hover': {
            backgroundColor: '#F8F9FA',
          },
          position: 'relative',
          ...(hoveredOver && {
            '&::after': {
              content: '""',
              position: 'absolute',
              bottom: '-5px',
              width: '90%',
              marginInline: 'auto',
              left: 0,
              right: 0,
              height: '1px',
              backgroundColor: theme.palette.primary.main,
            },
          }),
        }}
      >
        <Stack
          sx={{
            flexDirection: 'row',
            justifyContent: 'center',
            alignItems: 'center',
            py: 0.5,
            pl: 4,
            gap: 1,
            width: '100%',
          }}
        >
          <Stack
            sx={{
              flexDirection: 'row',
              justifyContent: 'flex-start',
              alignItems: 'center',
              gap: 0.5,
              width: 'calc(100% - 48px)',
            }}
          >
            <DragHandleOutlined
              color="secondary"
              sx={{
                visibility: showActions ? 'visible' : 'hidden',
                width: '24px',
                height: '24px',
              }}
            />
            <Icon sx={{ color, fontSize: '16px' }} />
            <Tooltip title={tooltipText}>
              <Stack
                sx={{
                  flexDirection: 'row',
                  justifyContent: 'flex-start',
                  alignItems: 'center',
                  gap: 0.5,
                  width: showActions ? 'calc(100% - 48px)' : 'calc(100% - 8px)',
                }}
              >
                <Typography
                  noWrap
                  variant="body2"
                  sx={{
                    textAlign: 'left',
                    maxWidth: isIncomplete ? 'calc(100% - 12px)' : '100%',
                    color: isIncomplete
                      ? theme.palette.warning.dark
                      : theme.palette.text.secondary,
                  }}
                >
                  {task.title}
                </Typography>
                {isIncomplete && (
                  <Stack
                    sx={{
                      width: '8px',
                      height: '8px',
                      borderRadius: '50%',
                      backgroundColor: 'warning.dark',
                    }}
                  />
                )}
              </Stack>
            </Tooltip>
          </Stack>
          <Stack
            sx={{
              flexDirection: 'row',
              justifyContent: 'center',
              alignItems: 'center',
              width: '40px',
              height: '40px',
              '& > *': {
                visibility: showActions ? 'visible' : 'hidden',
                width: !showActions ? '0px' : undefined,
              },
            }}
          >
            <IconsMenu
              options={options}
              onClick={handleOpenMenu}
              onClose={handleCloseMenu}
            />
          </Stack>
        </Stack>
      </ButtonBase>
    </Stack>
  );
};

export default TaskListItem;
