/**
 * @Move (SQPM)
 * Only used by the Performance module - move to Performance/
 */
import { Fragment } from 'react';
import Chart from 'react-apexcharts';

import { ApexOptions } from 'apexcharts';

import Avatar from '@material-hu/mui/Avatar';
import Box from '@material-hu/mui/Box';
import Tooltip from '@material-hu/mui/Tooltip';
import Typography from '@material-hu/mui/Typography';
import { colorPalette } from '@material-hu/theme/hugo/colors';

import { NineBoxUser } from 'src/types/performance';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getFullname } from 'src/utils/userUtils';

import ProfilePicture from '../ProfilePicture';

import ReviewHeatmapDrawer from './ReviewHeatmapDrawer';

type Props = {
  users: NineBoxUser[];
};

const getAvatarStyle = (x, y) => ({
  position: 'absolute',
  left: `calc(96px + (${x}% - ${(x / 100) * 180}px))`, // Locate left considering paddings
  bottom: `calc(92px + (${y}% - ${(y / 100) * 142}px))`, // Locate bottom considering paddings
});

const AVATAR_SIZE_PERCENTAGE = 60;

const calculateDistance = (user1, user2) => {
  const xDist = (user1.x - user2.x) * 10; // Convert x diff to %
  const yDist = (user1.y - user2.y) * 10; // Convert y diff to %
  return Math.sqrt(xDist ** 2 + yDist ** 2);
};

const groupUsers = positions => {
  const groups = [];
  const visited = new Array(positions.length).fill(false);

  positions.forEach((pos, index) => {
    if (!visited[index]) {
      const group = [];
      visited[index] = true;
      group.push(pos);

      for (let i = index + 1; i < positions.length; i++) {
        if (
          !visited[i] &&
          calculateDistance(pos, positions[i]) < AVATAR_SIZE_PERCENTAGE
        ) {
          visited[i] = true;
          group.push(positions[i]);
        }
      }

      groups.push(group);
    }
  });

  return groups;
};

const ReviewHeatmap = ({ users }: Props) => {
  const { handleOpen, component } = ReviewHeatmapDrawer();
  const { t } = useLokaliseTranslation(['backoffice_only']);

  const options: ApexOptions = {
    chart: {
      type: 'heatmap' as const,
      height: '100%',
      width: '100%',
      toolbar: {
        show: false,
      },
    },
    plotOptions: {
      heatmap: {
        enableShades: false,
        colorScale: {
          ranges: [
            { from: 0, to: 1, color: colorPalette.border.errorBorder },
            { from: 1, to: 2, color: colorPalette.hugoBackground.errorBg },
            { from: 2, to: 3, color: colorPalette.hugoBackground.warningBg },
            { from: 3, to: 4, color: colorPalette.hugoBackground.errorBg },
            { from: 4, to: 5, color: colorPalette.hugoBackground.warningBg },
            { from: 5, to: 6, color: colorPalette.hugoBackground.successBg },
            { from: 6, to: 7, color: colorPalette.hugoBackground.warningBg },
            { from: 7, to: 8, color: colorPalette.hugoBackground.successBg },
            { from: 8, to: 9, color: colorPalette.border.successBorder },
          ],
        },
      },
    },
    grid: {
      show: true,
      position: 'front',
      borderColor: colorPalette.border.neutralBorder,
      xaxis: {
        lines: {
          show: true,
        },
      },
      yaxis: {
        lines: {
          show: true,
        },
      },
    },
    dataLabels: {
      enabled: false,
    },
    tooltip: {
      enabled: false,
    },
    legend: {
      show: false,
    },
    xaxis: {
      categories: [
        t('backoffice_only:review_heatmap.insufficient'),
        t('backoffice_only:review_heatmap.sufficient'),
        t('backoffice_only:review_heatmap.outstanding'),
      ],
      labels: {
        offsetY: 3,
        style: {
          fontSize: '14px',
          fontWeight: 'normal',
          colors: ['#000'],
          fontFamily: 'Roboto',
        },
      },
    },
    yaxis: {
      labels: {
        rotate: -90,
        offsetX: 5,
        offsetY: -30,
        style: {
          fontSize: '14px',
          colors: ['#000'],
          fontFamily: 'Roboto',
        },
        padding: 0,
      },
    },
    states: {
      hover: {
        filter: {
          type: 'darken',
          value: 0.95,
        },
      },
      active: {
        filter: {
          type: 'darken',
          value: 0.8,
        },
      },
    },
  };

  const series = [
    {
      name: t('backoffice_only:review_heatmap.insufficient'),
      data: [0, 1, 2],
    },
    {
      name: t('backoffice_only:review_heatmap.sufficient'),
      data: [3, 4, 5],
    },
    {
      name: t('backoffice_only:review_heatmap.outstanding'),
      data: [6, 7, 8],
    },
  ];

  const usersMap = users.map(u => ({
    ...u,
    x: u.goalsScore || 0,
    y: u.formScore || 0,
  }));

  const groupedUsers = groupUsers(usersMap || []);

  return (
    <Box
      position="relative"
      width="100%"
      height="600px"
      sx={{
        boxShadow: 3,
        borderRadius: 1,
        pb: 9,
        pl: 9,
        pr: 0,
      }}
    >
      <Chart
        options={options}
        series={series}
        type="heatmap"
        height="100%"
        width="100%"
      />
      {groupedUsers.map((group, index) => (
        <Fragment key={index}>
          {group?.length > 1 && (
            <Tooltip
              title={group.map(u => getFullname(u.user)).join('\n')}
              PopperProps={{
                sx: {
                  '.MuiTooltip-tooltip': {
                    whiteSpace: 'pre-line',
                  },
                },
              }}
            >
              <Avatar
                onClick={() => handleOpen(group.map(u => u.user))}
                sx={{
                  ...getAvatarStyle(group[0].x, group[0].y),
                  backgroundColor: '#E6E7EB',
                  color: 'black',
                  '&:hover': {
                    cursor: 'pointer',
                    border: '2px solid #1B76D2',
                  },
                }}
              >
                {`+${group.length}`}
              </Avatar>
            </Tooltip>
          )}
          {group?.length === 1 && (
            <Tooltip title={getFullname(group[0].user)}>
              <Box sx={getAvatarStyle(group[0].x, group[0].y)}>
                <ProfilePicture
                  sx={{
                    '&:hover': {
                      cursor: 'pointer',
                      border: '2px solid #1B76D2',
                    },
                  }}
                  id={group[0].user.userId}
                  user={group[0].user}
                  size="medium"
                />
              </Box>
            </Tooltip>
          )}
        </Fragment>
      ))}
      <Box
        sx={{
          position: 'absolute',
          top: 0,
          left: 0,
          width: 64,
          height: '100%',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          border: '1px solid #E5E7EB',
          borderTop: 'none',
          borderLeft: 'none',
          borderBottom: 'none',
          backgroundColor: 'none',
        }}
      >
        <Typography
          variant="subtitle1"
          sx={{
            transform: 'rotate(-90deg)',
            whiteSpace: 'nowrap',
            mb: 10,
          }}
        >
          {t('backoffice_only:review_heatmap.potential')}
        </Typography>
      </Box>
      <Box
        sx={{
          position: 'absolute',
          bottom: 0,
          left: 0,
          width: '100%',
          height: 64,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          border: '1px solid #E5E7EB',
          borderLeft: 'none',
          borderRight: 'none',
          borderBottom: 'none',
          backgroundColor: 'none',
        }}
      >
        <Typography
          variant="subtitle1"
          sx={{ whiteSpace: 'nowrap', ml: 7 }}
        >
          {t('backoffice_only:review_heatmap.goals')}
        </Typography>
      </Box>
      {component}
    </Box>
  );
};

export default ReviewHeatmap;
