import { useMemo } from 'react';
import {
  Area,
  AreaChart,
  CartesianGrid,
  ResponsiveContainer,
  YAxis,
} from 'recharts';
import { useTheme } from 'styled-components';
import { chartColors } from '../../../style/theme';
import { addMissingDataPoint } from '../common/chartUtils';

type SparklineProps = {
  serie: {
    data: [number, number | null][];
    color?: string; // exa color code like '#ff0000'
  };
  startingTimeStamp: number;
  sampleDuration: number;
  sampleInterval: number;
  yAxisType?: 'default' | 'percentage';
};

/**
 * Sparkline is a simple dynamically sized area chart.
 * Used to show trends in data over time.
 * @param serie - The data series to display
 * @param startingTimeStamp - The starting timestamp in seconds
 * @param sampleDuration - The total duration in seconds to cover in the sparkline
 * @param sampleInterval - The interval in seconds between data points
 * @param yAxisType - The type of y-axis to display
 * @returns The sparkline component
 */
export function Sparkline({
  serie,
  startingTimeStamp,
  sampleDuration,
  sampleInterval,
  yAxisType,
}: SparklineProps) {
  const data = useMemo(() => {
    const dataMdp = addMissingDataPoint(
      serie.data,
      startingTimeStamp,
      sampleDuration,
      sampleInterval,
    );
    return dataMdp.map(([x, y]) => ({ x, y }));
  }, [serie.data]);
  const color = serie.color ?? chartColors.lineColor1;
  const strokeGridColor = useTheme().border;

  return (
    <ResponsiveContainer>
      <AreaChart data={data}>
        <defs>
          <linearGradient id={`gradient-${color}`} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={color} stopOpacity={0.7} />
            <stop offset="100%" stopColor={color} stopOpacity={0.1} />
          </linearGradient>
        </defs>
        <CartesianGrid
          horizontal={false}
          stroke={strokeGridColor}
          strokeOpacity={0.5}
        />
        <Area
          type="linear"
          dataKey="y"
          stroke={color}
          fill={`url(#gradient-${color})`}
          dot={false}
          activeDot={false}
          isAnimationActive={false}
        />
        {yAxisType === 'percentage' && <YAxis domain={[0, 100]} hide />}
      </AreaChart>
    </ResponsiveContainer>
  );
}
