/**
 * @deprecated — closest Hugo equivalent is `DonutChart` from `@material-hu/components/design-system/Charts/DonutChart`
 * but it renders a donut shape instead of a filled pie. Visual parity requires design sign-off before migration.
 *
 * Migration notes:
 * - Confirm with design whether `DonutChart` is an acceptable replacement for current pie consumers.
 * - If accepted, migrate consumers and delete this component.
 * - If not accepted, a new `PieChart` component must be created in `@material-hu`.
 */
import randomColor from 'randomcolor';

import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

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

type PieChartProps = {
  data: { value: number; color?: string; label: string }[];
  title?: string;
};

const PieChart = ({ data, title }: PieChartProps) => {
  return (
    <Stack
      sx={{
        borderStyle: 'solid',
        borderWidth: 1,
        borderRadius: 1,
        borderColor: 'divider',
      }}
    >
      <Stack>
        {title && (
          <Typography
            align="center"
            variant="h6"
          >
            {title}
          </Typography>
        )}
        <Stack sx={{ maxHeight: 300 }}>
          <DonutChart
            type="doughnut"
            data={{
              labels: data.map(item => item.label),
              datasets: [
                {
                  data: data.map(item => item.value),
                  backgroundColor: data.map(
                    item => item.color || randomColor({ seed: item.label }),
                  ),
                  hoverOffset: 3,
                },
              ],
            }}
            options={{
              cutout: 0,
              maintainAspectRatio: false,
              plugins: {
                legend: {
                  position: 'bottom',
                  labels: {
                    boxWidth: 10,
                    borderRadius: 5,
                    useBorderRadius: true,
                  },
                },
                tooltip: {
                  callbacks: {
                    label: context => {
                      const total = context.dataset.data.reduce(
                        (a, b) => a + b,
                        0,
                      );
                      const percentage = (
                        (context.parsed / total) *
                        100
                      ).toFixed(1);
                      return `${context.parsed} (${percentage}%)`;
                    },
                  },
                },
              },
            }}
          />
        </Stack>
      </Stack>
    </Stack>
  );
};

export default PieChart;
