import { type FC } from 'react';

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

import { type StreamTimeTick } from 'src/types/stream';

import { STREAM_METRICS } from '../../../constants';
import { getSparklinePoints, getTickTranslateX } from '../../../utils';

const { SPARKLINE } = STREAM_METRICS;

type MetricSparklineProps = {
  ready: boolean;
  values: number[];
  /** Elapsed-minute labels rendered under the chart (e.g. `0m`, `1m`) */
  ticks: StreamTimeTick[];
};

const MetricSparkline: FC<MetricSparklineProps> = props => {
  const { ready, values, ticks } = props;
  const theme = useTheme();
  const lineColor = theme.palette.new.action.button.background.primary.default;

  if (!ready)
    return (
      <Stack sx={{ minWidth: 0 }}>
        <Skeleton
          variant="rounded"
          width="100%"
          height={SPARKLINE.HEIGHT}
        />
      </Stack>
    );

  const points = values.length >= 2 ? getSparklinePoints(values) : [];
  const linePath = points
    .map((point, index) => `${index === 0 ? 'M' : 'L'}${point.x},${point.y}`)
    .join(' ');
  const lastPoint = points.at(-1);
  const areaPath = lastPoint
    ? `${linePath} L${lastPoint.x},${SPARKLINE.HEIGHT} L${points[0].x},${SPARKLINE.HEIGHT} Z`
    : '';

  return (
    <Stack sx={{ minWidth: 0 }}>
      <svg
        role="presentation"
        aria-hidden="true"
        width="100%"
        height={SPARKLINE.HEIGHT}
        viewBox={`0 0 ${SPARKLINE.WIDTH} ${SPARKLINE.HEIGHT}`}
        preserveAspectRatio="none"
        style={{ display: 'block' }}
      >
        {points.length > 0 && (
          <>
            <path
              d={areaPath}
              fill={lineColor}
              fillOpacity={SPARKLINE.AREA_OPACITY}
            />
            <path
              d={linePath}
              fill="none"
              stroke={lineColor}
              strokeWidth={SPARKLINE.STROKE_WIDTH}
              strokeLinecap="round"
              strokeLinejoin="round"
              vectorEffect="non-scaling-stroke"
            />
          </>
        )}
      </svg>
      <Stack
        sx={{
          position: 'relative',
          height: theme.spacing(2),
        }}
      >
        {ticks.map(tick => (
          <Typography
            key={tick.fraction}
            variant="globalXS"
            color="new.text.neutral.lighter"
            sx={{
              position: 'absolute',
              left: `${tick.fraction * 100}%`,
              transform: `translateX(${getTickTranslateX(tick.fraction)})`,
            }}
          >
            {tick.label}
          </Typography>
        ))}
      </Stack>
    </Stack>
  );
};

export default MetricSparkline;
