import { getColors } from '@/themes/getColors';
import { Box, Tooltip as MuiTooltip, tooltipClasses } from '@mui/material';
import { styled, useTheme } from '@mui/material/styles';
import { PropsWithChildren } from 'react';

type GetVariantStyleProps = {
  color: string;
  theme: any;
  labelColor: string;
};

function getVariantStyle({ color, theme, labelColor }: GetVariantStyleProps) {
  const colors = getColors(theme, color as any);
  const { main, contrastText } = colors;
  const colorValue = color ? color : '';

  if (['primary', 'secondary', 'info', 'success', 'warning', 'error'].includes(colorValue)) {
    return {
      [`& .${tooltipClasses.tooltip}`]: {
        backgroundColor: main,
        color: labelColor ? labelColor : contrastText
      },
      [`& .${tooltipClasses.arrow}`]: {
        color: main
      }
    };
  } else {
    return {
      [`& .${tooltipClasses.tooltip}`]: {
        backgroundColor: colorValue,
        color: labelColor ? labelColor : contrastText,
        boxShadow: theme.shadows[1]
      },
      [`& .${tooltipClasses.arrow}`]: {
        color: colorValue
      }
    };
  }
}

type TooltipStyleProps = PropsWithChildren<{
  color: string;
  labelColor: string;
  title: string;
}>;

const TooltipStyle = styled(
  // @ts-ignore
  ({ className, ...props }: TooltipStyleProps) => <MuiTooltip {...props} classes={{ popper: className }} />,
  {
    shouldForwardProp: (prop) => prop !== 'color' && prop !== 'labelColor'
  }
)(({ theme, color, labelColor }) => ({
  ...(color && getVariantStyle({ color, theme, labelColor }))
}));

type TooltipProps = PropsWithChildren<{
  arrow: boolean;
  labelColor?: string;
  rest: any;
}>;

function Tooltip({ children, arrow, labelColor = '', ...rest }: TooltipProps) {
  const theme = useTheme();
  return (
    <Box display="flex">
      {/* @ts-ignore */}
      <TooltipStyle arrow={arrow} {...rest} theme={theme} labelColor={labelColor}>
        {children}
      </TooltipStyle>
    </Box>
  );
}

export { Tooltip };
export type { TooltipProps };
