import { Box, Stack, Typography } from '@mui/material';

// Dependency-free donut chart. data: [{ label, value, color }]
export default function DonutChart({ data = [], size = 180, thickness = 26, centerLabel, centerValue }) {
  const total = data.reduce((s, d) => s + d.value, 0) || 1;
  const r = (size - thickness) / 2;
  const c = 2 * Math.PI * r;
  let offset = 0;

  return (
    <Stack
      direction={{ xs: 'column', sm: 'row' }}
      spacing={3}
      alignItems="center"
      justifyContent="center"
      sx={{ flexWrap: 'wrap' }}
    >
      <Box sx={{ position: 'relative', width: size, maxWidth: '100%', aspectRatio: '1 / 1' }}>
        <svg width="100%" height="100%" viewBox={`0 0 ${size} ${size}`}>
          <g transform={`rotate(-90 ${size / 2} ${size / 2})`}>
            <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="#F0F0F0" strokeWidth={thickness} />
            {data.map((d, i) => {
              const len = (d.value / total) * c;
              const seg = (
                <circle
                  key={i}
                  cx={size / 2}
                  cy={size / 2}
                  r={r}
                  fill="none"
                  stroke={d.color}
                  strokeWidth={thickness}
                  strokeDasharray={`${len} ${c - len}`}
                  strokeDashoffset={-offset}
                  strokeLinecap="butt"
                />
              );
              offset += len;
              return seg;
            })}
          </g>
        </svg>
        <Box sx={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
          <Typography variant="h3" sx={{ fontWeight: 700 }}>{centerValue ?? total}</Typography>
          <Typography variant="caption" color="text.secondary">{centerLabel ?? 'Total'}</Typography>
        </Box>
      </Box>
      <Stack spacing={1.25}>
        {data.map((d) => (
          <Stack key={d.label} direction="row" spacing={1} alignItems="center">
            <Box sx={{ width: 10, height: 10, borderRadius: '3px', bgcolor: d.color }} />
            <Typography variant="body2" color="text.secondary" sx={{ minWidth: 80 }}>{d.label}</Typography>
            <Typography variant="subtitle2">{d.value.toLocaleString('en-IN')}</Typography>
          </Stack>
        ))}
      </Stack>
    </Stack>
  );
}
