import { type MouseEvent, type PropsWithChildren, useState } from 'react';

import AddCircleOutlineOutlined from '@material-hu/icons/material/AddCircleOutlineOutlined';
import DragHandleOutlined from '@material-hu/icons/material/DragHandleOutlined';
import ReportOutlined from '@material-hu/icons/material/ReportOutlined';
import ButtonBase from '@material-hu/mui/ButtonBase';
import Collapse from '@material-hu/mui/Collapse';
import IconButton from '@material-hu/mui/IconButton';
import Paper from '@material-hu/mui/Paper';
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 {
  getModuleElementId,
  validateModule,
} from 'src/pages/dashboard/Learning/Courses/New/utils';
import { type Module } from 'src/pages/dashboard/Learning/Courses/types';
import { IconType } from 'src/types/icons';
import { useLokaliseTranslation } from 'src/utils/i18n';

import CustomIcon from 'src/components/CustomIcon';

export type ModuleListItemProps = PropsWithChildren<
  StackProps & {
    index: number;
    module: Module;
    onSelect?: (event: MouseEvent<HTMLButtonElement>) => void;
    onDelete?: () => void;
    onCreateTask?: (event: MouseEvent<HTMLButtonElement>) => void;
    expanded?: boolean;
    selectedModule?: boolean;
    selectedInnerTask?: boolean;
    showValidation?: boolean;
  }
>;

export const ModuleListItem = ({
  index,
  module,
  onSelect = () => null,
  onDelete = () => null,
  onCreateTask = () => null,
  selectedModule = false,
  selectedInnerTask = false,
  showValidation = false,
  expanded = true,
  children,
  ...stackProps
}: ModuleListItemProps) => {
  const [showActions, setShowActions] = useState(false);
  const [openMenu, setOpenMenu] = useState(false);

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

  const selected = selectedModule || selectedInnerTask;

  const handleCreateTask = (event: MouseEvent<HTMLButtonElement>) => {
    event.stopPropagation();
    onCreateTask(event);
  };

  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 isIncomplete = showValidation && !validateModule(module);

  return (
    <Stack
      component={Paper}
      elevation={24}
      border={0}
      sx={{
        width: '100%',
        border: '2px solid',
        borderColor: selected ? theme.palette.primary.main : 'transparent',
      }}
      {...stackProps}
    >
      <ButtonBase
        id={getModuleElementId(index)}
        component="div"
        role="button"
        onClick={onSelect}
        onMouseOver={handleMouseOver}
        onMouseOut={handleMouseOut}
        disableRipple
        sx={{
          backgroundColor: selectedModule
            ? '#F3F4F6'
            : theme.palette.background.paper,
          borderTopLeftRadius: theme.spacing(1),
          borderTopRightRadius: theme.spacing(1),
          borderBottomLeftRadius: expanded ? undefined : theme.spacing(1),
          borderBottomRightRadius: expanded ? undefined : theme.spacing(1),
          '&:hover': {
            backgroundColor: '#F8F9FA',
          },
        }}
      >
        <Stack
          sx={{
            flexDirection: 'row',
            justifyContent: 'center',
            alignItems: 'center',
            py: 0.5,
            width: '100%',
            borderRadius: 'inherit',
          }}
        >
          <IconButton
            id="expand-module-button"
            aria-label={t('general:expand')}
          >
            <DragHandleOutlined />
          </IconButton>
          <Typography
            component="div"
            sx={{
              display: 'flex',
              alignItems: 'center',
              gap: 1,
              width: showActions ? 'calc(100% - 120px)' : 'calc(100% - 40px)',
            }}
          >
            <CustomIcon
              icon={module.icon}
              size={14}
              sx={{
                mt: module.icon.type === IconType.IMAGE ? -1 : undefined,
              }}
            />
            <Typography
              noWrap
              sx={{
                maxWidth: 'calc(100% - 22px)',
                fontWeight: '500',
                textAlign: 'left',
              }}
            >
              {module.title}
            </Typography>
            {isIncomplete && <ReportOutlined color="error" />}
          </Typography>
          <Stack
            sx={{
              flexDirection: 'row',
              justifyContent: 'center',
              alignItems: 'center',
              width: '80px',
              '& > *': {
                ...(showActions && {
                  visibility: 'visible',
                  width: 'revert',
                }),
                ...(!showActions && {
                  visibility: 'hidden',
                  width: 0,
                  p: 0,
                  m: 0,
                }),
              },
            }}
          >
            <Tooltip title={t('course.lesson.add')}>
              <IconButton
                id="add-task-sidebar-button"
                aria-label={t('course.lesson.new_module')}
                onClick={handleCreateTask}
              >
                <AddCircleOutlineOutlined />
              </IconButton>
            </Tooltip>
            <IconsMenu
              options={options}
              onClick={handleOpenMenu}
              onClose={handleCloseMenu}
            />
          </Stack>
        </Stack>
      </ButtonBase>
      <Collapse in={expanded}>
        <Stack sx={{ justifyContent: 'center', alignItems: 'center' }}>
          {children}
        </Stack>
      </Collapse>
    </Stack>
  );
};

export default ModuleListItem;
