import { FC, useState } from 'react';

import {
  IconEdit,
  IconGripVertical,
  IconTrash,
} from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import MenuList from '@material-hu/components/composed-components/MenuList';
import HuBadge from '@material-hu/components/design-system/Badge';

import type { ViewListItem } from 'src/pages/dashboard/serviceManagement/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

type Props = {
  view: ViewListItem;
  selected: boolean;
  hasBubble?: boolean;
  onRename: (view: ViewListItem) => void;
  onDelete: (view: ViewListItem) => void;
  onSelect: (viewId: string) => void;
};

const ViewListItem: FC<Props> = ({
  view,
  selected,
  hasBubble = false,
  onRename,
  onDelete,
  onSelect,
}) => {
  const { t } = useLokaliseTranslation('service_management');
  const theme = useTheme();

  const [isHovered, setIsHovered] = useState(false);

  const getBackgroundColor = () => {
    if (selected) {
      return theme.palette.new.action.button.background.tertiary.focus;
    }
    if (isHovered) {
      return theme.palette.new.action.button.background.tertiary.hover;
    }
    return 'transparent';
  };

  return (
    <Stack
      onClick={() => onSelect(view.id)}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
      sx={{
        borderRadius: ({ shape }) => shape.borderRadiusL,
        py: 1.5,
        pl: isHovered ? 2.5 : 5,
        pr: 1,
        cursor: 'pointer',
        height: 48,
        flexDirection: 'row',
        gap: 0.5,
        alignItems: 'center',
        backgroundColor: getBackgroundColor(),
        transition: 'background-color 400ms ease-out',
      }}
    >
      {isHovered && (
        <IconGripVertical
          size={16}
          color={theme.palette.new.text.neutral.lighter}
          style={{
            cursor: 'grab',
          }}
        />
      )}
      {hasBubble && (
        <HuBadge
          variant="dot"
          color="primary"
        />
      )}
      <Typography
        variant="globalS"
        noWrap
        sx={{
          width: 'calc(100% - 55px)',
          fontWeight: 'fontWeightSemiBold',
          color: ({ palette }) =>
            selected
              ? palette.new.text.neutral.default
              : palette.new.text.neutral.lighter,
        }}
      >
        {view.name}
      </Typography>
      {isHovered && (
        <MenuList
          options={[
            {
              Icon: IconEdit,
              title: t('rename'),
              onClick: () => onRename(view),
            },
            {
              Icon: IconTrash,
              title: t('delete'),
              onClick: () => onDelete(view),
            },
          ]}
          size="small"
        />
      )}
    </Stack>
  );
};

export default ViewListItem;
