import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';

import BarChart from '@material-hu/components/design-system/Charts/BarChart';

import { EnpsSegment, EnpsChart, ComparisionSurvey, Nullable } from '../types';
import { insertIf } from 'src/utils/arrays';

type EnpsBarChartProps = {
  npsDiffStats: EnpsSegment[];
  comparisionSurvey?: Nullable<ComparisionSurvey>;
  npsChart?: EnpsChart;
  surveyName?: string;
};

const EnpsBarChart = ({
  npsDiffStats,
  npsChart,
  comparisionSurvey,
  surveyName = '',
}: EnpsBarChartProps) => {
  const theme = useTheme();
  const barColor = theme.palette.new.graphics.brand[500];
  const secondBarColor =
    '#' +
    (0xffffff ^ parseInt(barColor.slice(1), 16)).toString(16).padStart(6, '0');

  const comparedSurvey = comparisionSurvey?.id;
  const hasComparisonSurvey = !!comparedSurvey;

  const npsDiff = npsDiffStats.map(d => d.stats?.[0].score);
  const npsParents =
    npsChart?.hierarchy.map(({ parentId, ...rest }) => rest) || [];
  const npsStats = npsChart ? npsParents.concat(npsChart?.stats) : [];

  const seriesData = npsStats.map(e => e.score);
  const labels = npsStats.map(e => e.title);

  return (
    <Stack sx={{ height: '250px' }}>
      <BarChart
        type="bar"
        data={{
          labels,
          datasets: [
            ...insertIf(!!comparedSurvey, {
              label: comparisionSurvey?.title,
              data: npsDiff,
              backgroundColor: secondBarColor,
            }),
            {
              label: comparedSurvey ? surveyName : '',
              data: seriesData,
              backgroundColor: barColor,
            },
          ],
        }}
        options={{
          maintainAspectRatio: false,
          plugins: {
            legend: {
              display: false,
            },
            tooltip: {
              callbacks: {
                label: context => {
                  const value = context.parsed.y;
                  const hasMissingComparison =
                    npsDiffStats?.[context.dataIndex]?.stats?.[0]
                      ?.missingComparison;
                  const hasPassedThreshold =
                    npsDiffStats?.[context.dataIndex]?.stats?.[0]
                      ?.passedThreshold;
                  const statPassedThreshold =
                    npsStats?.[context.dataIndex]?.passedThreshold;

                  if (
                    ((hasComparisonSurvey &&
                      (hasMissingComparison || !hasPassedThreshold)) ||
                      !statPassedThreshold) &&
                    value === 0
                  )
                    return '--';
                  return value === 0 ? '0' : String(value);
                },
              },
            },
          },
          scales: {
            x: {
              grid: {
                display: false,
              },
              border: {
                display: false,
              },
              ticks: {
                display: false,
              },
            },
            y: {
              min: -100,
              max: 100,
              ticks: {
                stepSize: 50,
                callback: (value: number | string) => Number(value).toFixed(0),
                font: {
                  family: theme.typography.fontFamily,
                },
              },
              grid: {
                color: theme.palette.new.border.neutral.divider,
              },
              border: {
                display: true,
                color: theme.palette.new.border.neutral.divider,
              },
            },
          },
          elements: {
            bar: {
              borderRadius: 5,
              borderSkipped: 'bottom',
            },
          },
        }}
        height={250}
      />
    </Stack>
  );
};

export default EnpsBarChart;
