import { useTranslation } from 'react-i18next';

import TableCell from '@design-system/Table/components/TableCell';
import Tooltip from '@design-system/Tooltip';
import { Typography, tooltipClasses, useTheme } from '@mui/material';

import usePopover from '../../../../../hooks/usePopover';
import { getColorScoreThreshold } from '../../constants';
import { type Nullable, ScoreType } from '../../types';
import { formatScore } from '../utils';

import ScoreComparisonPopover from './ScoreComparisonPopover';

const getPrefixSign = (value: number) => {
  if (value === 0 || value < 0) return '';
  return '+';
};

type HeatScoreCellProps = {
  score: Nullable<number>;
  difference: Nullable<number>;
  baseScore: Nullable<number>;
  scoreType: ScoreType;
  isTotal?: boolean;
};

const HeatScoreCell = ({
  score,
  difference,
  isTotal,
  scoreType,
  baseScore,
}: HeatScoreCellProps) => {
  const theme = useTheme();
  const { t } = useTranslation('material_hu_only');

  const { id, isOpen, anchorEl, openPopover, closePopover } = usePopover();

  const getBackgroundColor = () => {
    if (scoreType === ScoreType.DIFFERENCE) {
      if (!difference) {
        return theme.palette.new.background.elements.default;
      }

      return difference > 0
        ? theme.palette.new.background.feedback.success
        : theme.palette.new.background.feedback.error;
    }

    if (score === null) {
      return theme.palette.new.background.elements.default;
    }

    const matchedColor = getColorScoreThreshold(theme).find(
      ({ from, to }) => (score > from || from === 0) && score <= to,
    );
    return matchedColor
      ? matchedColor.color
      : theme.palette.new.background.elements.default;
  };

  const getTotalBackgroundColor = () => {
    if (scoreType === ScoreType.DIFFERENCE) {
      if (!difference) {
        return theme.palette.new.background.elements.default;
      }

      return difference > 0
        ? theme.palette.new.graphics.success[600]
        : theme.palette.new.graphics.error[600];
    }

    return theme.palette.new.background.elements.inverted;
  };

  const getTextColor = () => {
    if (scoreType === ScoreType.DIFFERENCE || score === null) {
      return theme.palette.new.text.neutral.default;
    }

    return score >= 0.4
      ? theme.palette.new.text.neutral.inverted
      : theme.palette.new.text.neutral.default;
  };

  const getTotalTextColor = () => {
    if (scoreType === ScoreType.DIFFERENCE && !difference) {
      return theme.palette.new.text.neutral.default;
    }

    return theme.palette.new.text.neutral.inverted;
  };

  const getDisplayScore = () => {
    if (
      (scoreType === ScoreType.DIFFERENCE && difference === null) ||
      (scoreType === ScoreType.SCORE && score === null)
    ) {
      return (
        <Tooltip
          title={t('people_experience.not_enough_data')}
          slotProps={{
            tooltip: {
              sx: {
                border: `1px solid ${theme.palette.new.border.neutral.default}`,
                [`& .${tooltipClasses.arrow}:before`]: {
                  border: `1px solid ${theme.palette.new.border.neutral.default}`,
                },
              },
            },
          }}
        >
          <Typography
            sx={{ fontSize: 'inherit', width: '100%', height: '100%' }}
          >
            --
          </Typography>
        </Tooltip>
      );
    }

    if (scoreType === ScoreType.DIFFERENCE) {
      return `${getPrefixSign(difference as number)} ${formatScore(
        difference as number,
      )}`;
    }

    return formatScore(score as number);
  };

  const hasPopover =
    baseScore !== null && score !== null && difference !== null;

  return (
    <>
      <TableCell
        colSpan={2}
        align="center"
        sx={{
          backgroundColor: isTotal
            ? getTotalBackgroundColor()
            : getBackgroundColor(),
          color: isTotal ? getTotalTextColor() : getTextColor(),
          '& .MuiTypography-root': {
            color: 'inherit',
          },
        }}
        onMouseEnter={openPopover}
        onMouseLeave={closePopover}
      >
        {getDisplayScore()}
      </TableCell>
      {hasPopover && (
        <ScoreComparisonPopover
          id={id}
          open={isOpen}
          anchorEl={anchorEl}
          onClose={closePopover}
          baseScore={baseScore}
          score={score}
          difference={difference}
        />
      )}
    </>
  );
};

export default HeatScoreCell;
