import DonutChart from '@design-system/Charts/DonutChart';
import Tooltip from '@design-system/Tooltip';
import { Stack, Typography, useTheme } from '@mui/material';

import { type SemiDonutChartProps } from './types';
import { calculateFillPercentage } from './utils';

const FALLBACK_NULL_VALUE = -100;

const SemiDonutChart = ({
  value,
  nullValueTooltip,
  slotProps,
}: SemiDonutChartProps) => {
  const theme = useTheme();
  const fillPercentage = calculateFillPercentage(value || FALLBACK_NULL_VALUE);

  const options = {
    rotation: -90,
    circumference: 180,
    cutout: '80%',
    plugins: {
      tooltip: { enabled: false },
      legend: { display: false },
      datalabels: { display: false },
    },
    maintainAspectRatio: false,
  };

  return (
    <Stack
      {...slotProps?.root}
      sx={{
        position: 'relative',
        height: 120,
        pb: 2,
        flexShrink: 0,
        flexGrow: 0,
        boxSizing: 'border-box',
        '& canvas:nth-of-type(2)': { position: 'absolute', top: 0 },
        ...slotProps?.root?.sx,
      }}
    >
      <DonutChart
        type="doughnut"
        data={{
          datasets: [
            {
              data: [100],
              backgroundColor: [theme.palette.new.graphics.brand[100]],
              borderWidth: 0,
              borderRadius: 50,
            },
          ],
        }}
        options={{ ...options, animation: false }}
      />
      <DonutChart
        type="doughnut"
        data={{
          datasets: [
            {
              data: [fillPercentage, 100 - fillPercentage],
              backgroundColor: [
                theme.palette.new.graphics.brand[500],
                'transparent',
              ],
              borderWidth: 0,
              borderRadius: 50,
            },
          ],
        }}
        options={options}
      />
      <Stack
        sx={{
          position: 'absolute',
          bottom: '20%',
          left: '50%',
          transform: 'translateX(-50%)',
        }}
      >
        <Tooltip
          description={nullValueTooltip}
          disableTooltip={value !== null || !nullValueTooltip}
        >
          <Typography
            variant="globalXL"
            fontWeight="fontWeightSemiBold"
          >
            {value ?? '--'}
          </Typography>
        </Tooltip>
      </Stack>
      <Typography
        variant="globalXS"
        sx={{
          position: 'absolute',
          left: 40,
          bottom: -8,
          color: theme => theme.palette.new.text.neutral.lighter,
        }}
      >
        -100
      </Typography>
      <Typography
        variant="globalXS"
        sx={{
          position: 'absolute',
          right: 44,
          bottom: -8,
          color: theme => theme.palette.new.text.neutral.lighter,
        }}
      >
        100
      </Typography>
    </Stack>
  );
};

export default SemiDonutChart;
