import React from 'react';
import { G, Line } from 'react-native-svg';
import { useTheme } from '../../../theme';
import type { AxisCoordinates, YAxisConfig } from '../types';
import { DASH_ARRAY } from './constants';
import useGenerateTicks from './hooks/useGenerateTicks';
import useScaleLinearY from './hooks/useScaleLinearY';

export type YAxisGridProps = {
  yAxisConfig: Omit<YAxisConfig, 'labels'> & { minValue?: number };
  coordinates: AxisCoordinates;
};

const YAxisGrid = ({ yAxisConfig, coordinates }: YAxisGridProps) => {
  const theme = useTheme();
  const { maxValue, minValue, step, tick } = yAxisConfig;
  const { xStart, xEnd, yStart, yEnd } = coordinates;
  const {
    colors: { gridStroke },
  } = theme.__hd__.chart;

  const maxValueOrZero = maxValue || 0;
  const minValueOrZero = minValue || 0;

  const scaleY = useScaleLinearY({
    maxValue: maxValueOrZero,
    minValue: minValueOrZero,
    yStart,
    yEnd,
  });

  const tickInterval = tick?.interval || step;

  const ticks = useGenerateTicks({
    maxValue: maxValueOrZero,
    minValue: minValueOrZero,
    step: tickInterval,
  });

  return (
    <G testID="y-axis-grid">
      {ticks.map((value) => (
        <Line
          testID={`y-axis-grid-${value}`}
          key={value}
          x1={xStart}
          y1={scaleY(value)}
          x2={xEnd}
          y2={scaleY(value)}
          stroke={gridStroke}
          strokeDasharray={DASH_ARRAY}
        />
      ))}
    </G>
  );
};

export default YAxisGrid;
