import { type FC, memo, useCallback, useMemo } from 'react';

import { IconEyeClosed } from '@material-hu/icons/tabler';
import { Typography, useTheme } from '@material-hu/mui/index';
import Stack from '@material-hu/mui/Stack/Stack';

import HuMenuList, {
  type MenuListProps,
} from '@material-hu/components/composed-components/MenuList';
import Tag from '@material-hu/components/composed-components/Tag';
import HuPills from '@material-hu/components/design-system/Pills';
import HuTableCell from '@material-hu/components/design-system/Table/components/TableCell';
import HuTableRow from '@material-hu/components/design-system/Table/components/TableRow';
import HuTooltip from '@material-hu/components/design-system/Tooltip';

import { CopyTypePath } from 'src/types/deeplinks';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { namedFormatUTCDate } from 'src/utils/timeUtils';
import { getFullname } from 'src/utils/userUtils';

import CopyLink from 'src/components/CopyLink/CopyLink';

import TypographyOverflowTooltip from '../../components/TableCellOverflowTooltip';
import { type ServiceItemTableData } from '../../types';
import { getPillTypeFromServiceItem } from '../../utils';

import {
  FIRST_COLUMN_MIN_WIDTH,
  LAST_COLUMN_MIN_WIDTH,
  STICKY_LEFT_SX,
  STICKY_RIGHT_SX,
} from './ServicesTable.constants';

type Props = {
  serviceItem: ServiceItemTableData;
  isHovered: boolean;
  isTagsMenuActive: boolean;
  canEditOrCreateTags: boolean;
  getActions: (serviceItem: ServiceItemTableData) => MenuListProps['options'];
  showCategoryColumn: boolean;
  showStatusColumn: boolean;
  showCreatedAtColumn: boolean;
  showLastUpdatedColumn: boolean;
  showVisibilityColumn: boolean;
  showTagsColumn: boolean;
  setHoveredRow: (id: string | null) => void;
  onOpenTagsMenu: (
    serviceItem: ServiceItemTableData,
    e: React.MouseEvent<HTMLDivElement>,
  ) => void;
  onActionMenuClick: (serviceItem: ServiceItemTableData) => void;
};

const ServicesTableRow: FC<Props> = ({
  serviceItem,
  isHovered,
  isTagsMenuActive,
  canEditOrCreateTags,
  getActions,
  showCategoryColumn,
  showStatusColumn,
  showCreatedAtColumn,
  showLastUpdatedColumn,
  showVisibilityColumn,
  showTagsColumn,
  setHoveredRow,
  onOpenTagsMenu,
  onActionMenuClick,
}) => {
  const actions = useMemo(
    () => getActions(serviceItem),
    [getActions, serviceItem],
  );

  const theme = useTheme();
  const { t } = useLokaliseTranslation([
    'service_management',
    'general',
    'workflows',
  ]);

  const handleMouseEnter = useCallback(
    () => setHoveredRow(serviceItem.id),
    [setHoveredRow, serviceItem.id],
  );
  const handleMouseLeave = useCallback(
    () => setHoveredRow(null),
    [setHoveredRow],
  );

  const handleOpenTagsMenuClick = useCallback(
    (e: React.MouseEvent<HTMLDivElement>) => onOpenTagsMenu(serviceItem, e),
    [onOpenTagsMenu, serviceItem],
  );

  const handleActionMenuClick = useCallback(
    () => onActionMenuClick(serviceItem),
    [onActionMenuClick, serviceItem],
  );

  return (
    <HuTableRow
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
    >
      <HuTableCell
        variant="titleField"
        sx={{
          minWidth: FIRST_COLUMN_MIN_WIDTH,
          ...STICKY_LEFT_SX,
          borderRight: ({ palette }) =>
            `1px solid ${palette.new.border.neutral.default}`,
        }}
      >
        <Stack
          sx={{
            flexDirection: 'row',
            alignItems: 'center',
            gap: 1,
            maxWidth: 350,
          }}
        >
          <TypographyOverflowTooltip
            text={serviceItem.name}
            typographyProps={{
              variant: 'globalS',
              sx: {
                color: ({ palette }) => palette.new.text.neutral.default,
              },
            }}
          />
          <CopyLink
            type={CopyTypePath.WORKFLOWS}
            id={serviceItem.id}
            hoveredIconColor={theme.palette.primary.main}
            IconButtonProps={{
              sx: {
                visibility: isHovered ? 'visible' : 'hidden',
              },
            }}
          />
        </Stack>
      </HuTableCell>
      {showCategoryColumn && (
        <HuTableCell>
          <Stack sx={{ maxWidth: 160 }}>
            <TypographyOverflowTooltip
              text={serviceItem.category?.name ?? '-'}
              typographyProps={{
                variant: 'globalS',
                sx: {
                  color: ({ palette }) => palette.new.text.neutral.default,
                },
              }}
            />
          </Stack>
        </HuTableCell>
      )}
      {showStatusColumn && (
        <HuTableCell>
          {serviceItem.status && (
            <HuPills
              label={t(serviceItem.status)}
              size="small"
              hasIcon={false}
              type={getPillTypeFromServiceItem(serviceItem)}
            />
          )}
        </HuTableCell>
      )}
      {showCreatedAtColumn && (
        <HuTableCell>
          <Stack sx={{ flex: 1 }}>
            <Typography
              variant="globalS"
              sx={{
                color: ({ palette }) => palette.new.text.neutral.default,
              }}
            >
              {namedFormatUTCDate(serviceItem.createdAt)}
            </Typography>
            {serviceItem.createdBy && (
              <Typography
                variant="globalXS"
                sx={{
                  color: ({ palette }) => palette.new.text.neutral.lighter,
                  maxWidth: 350,
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                }}
              >{`${t('by')} ${getFullname(serviceItem.createdBy)}`}</Typography>
            )}
          </Stack>
        </HuTableCell>
      )}
      {showLastUpdatedColumn && (
        <HuTableCell>
          <Stack sx={{ flex: 1 }}>
            <Typography
              variant="globalS"
              sx={{
                color: ({ palette }) => palette.new.text.neutral.default,
              }}
            >
              {namedFormatUTCDate(serviceItem.updatedAt)}
            </Typography>
            {serviceItem.updatedBy && (
              <Typography
                variant="globalXS"
                sx={{
                  color: ({ palette }) => palette.new.text.neutral.lighter,
                  maxWidth: 350,
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                }}
              >{`${t('by')} ${getFullname(serviceItem.updatedBy)}`}</Typography>
            )}
          </Stack>
        </HuTableCell>
      )}
      {showVisibilityColumn && (
        <HuTableCell>
          {serviceItem.hidden && (
            <HuTooltip description={t('non_visible_service_item')}>
              <IconEyeClosed color={theme.palette.new.text.neutral.default} />
            </HuTooltip>
          )}
        </HuTableCell>
      )}
      {showTagsColumn && (
        <HuTableCell
          sx={{
            cursor: canEditOrCreateTags ? 'pointer' : 'default',
            backgroundColor: isTagsMenuActive
              ? theme.palette.new.background.elements.grey
              : undefined,
            border: ({ palette }) =>
              isTagsMenuActive
                ? `1px solid ${palette.newBase?.brand[500]}`
                : undefined,
            '&:hover': {
              backgroundColor: ({ palette }) =>
                palette.new.background.elements.grey,
            },
            maxWidth: 380,
          }}
          onClick={canEditOrCreateTags ? handleOpenTagsMenuClick : undefined}
        >
          <Stack
            sx={{
              width: 1,
              gap: 1,
              flexDirection: 'row',
              flexWrap: 'nowrap',
              overflow: 'hidden',
            }}
          >
            {serviceItem.tags?.map(tag => (
              <Tag
                key={tag.id}
                label={tag.name}
                variant={tag.color}
              />
            ))}
          </Stack>
        </HuTableCell>
      )}
      <HuTableCell
        align="center"
        sx={{
          minWidth: LAST_COLUMN_MIN_WIDTH,
          borderLeft: ({ palette }) =>
            `1px solid ${palette.new.border.neutral.default}`,
          ...STICKY_RIGHT_SX,
        }}
      >
        {actions.length > 0 && (
          <HuMenuList
            size="small"
            position="right"
            options={actions}
            onClick={handleActionMenuClick}
          />
        )}
      </HuTableCell>
    </HuTableRow>
  );
};

export default memo(ServicesTableRow);
