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 { useLokaliseTranslation } from 'src/utils/i18n';

import CsatChartSkeleton from './CsatChartSkeleton';

type CsatChartProps = {
  data: number[];
  loading: boolean;
};

const CsatChart = ({ data, loading }: CsatChartProps) => {
  const theme = useTheme();
  const { t } = useLokaliseTranslation('service_management');

  const labels = [
    ['1', `${t('CSAT_1_RATING')}`],
    ['2', `${t('CSAT_2_RATING')}`],
    ['3', `${t('CSAT_3_RATING')}`],
    ['4', `${t('CSAT_4_RATING')}`],
    ['5', `${t('CSAT_5_RATING')}`],
  ];

  if (loading) return <CsatChartSkeleton />;

  return (
    <Stack sx={{ height: 250 }}>
      <BarChart
        type="bar"
        data={{
          labels,
          datasets: [
            {
              data,
              backgroundColor: theme.palette.newBase?.brand[500],
              borderRadius: 8,
              borderSkipped: 'start',
              hoverBackgroundColor: theme.palette.newBase?.brand[600],
            },
          ],
        }}
        options={{
          maintainAspectRatio: false,
          plugins: {
            legend: { display: false },
            tooltip: {
              titleFont: {
                family: 'Roboto',
                size: 16,
                weight: 600,
              },
              bodyFont: {
                family: 'Roboto',
                size: 14,
              },
              callbacks: {
                title: items => {
                  return items[0].label.split(',')[1];
                },
                label: item => {
                  const dataset = item.dataset.data as number[];

                  const totalSum = dataset.reduce(
                    (acc: number, curr: number) => acc + curr,
                    0,
                  );
                  const value = dataset[item.dataIndex];

                  const percentage =
                    ((value / totalSum) * 100).toFixed(2) + '%';

                  return `${percentage} (${value})`;
                },
              },
            },
          },
          scales: {
            x: { grid: { display: false } },
            y: {
              ticks: {
                stepSize: 1,
              },
              beginAtZero: true,
              grid: {
                color: theme.palette.new.border.neutral.default,
              },
              border: {
                dash: [5, 5],
              },
            },
          },
        }}
      />
    </Stack>
  );
};

export default CsatChart;
