import {memo} from 'react';
import Animated, {
  clamp,
  SharedValue,
  useAnimatedProps,
} from 'react-native-reanimated';
import {Rect} from 'react-native-svg';

import {
  BAR_RX,
  BAR_WIDTH,
  MAX_BAR_HEIGHT,
  MIN_BAR_HEIGHT,
} from '../../../constants';

const AnimatedRect = Animated.createAnimatedComponent(Rect);

interface Props {
  x: number;
  index: number;
  fill: string;
  maxBarHeight?: number;
  normalizedBarHeights: SharedValue<number[]>;
}

export const WaveformBar = memo(
  ({
    x,
    index,
    fill,
    maxBarHeight = MAX_BAR_HEIGHT,
    normalizedBarHeights,
  }: Props) => {
    const animatedProps = useAnimatedProps(() => {
      // Read from END of array: index=0 → newest (rightmost), index=N → oldest.
      // Works for any array size — new samples always appear at the right edge.
      const arr = normalizedBarHeights.value;
      const h = arr[arr.length - 1 - index] ?? 0;
      const normalizedHeight = clamp(
        h * maxBarHeight,
        MIN_BAR_HEIGHT,
        maxBarHeight,
      );
      return {
        height: normalizedHeight,
        y: maxBarHeight / 2 - normalizedHeight / 2,
      };
    });

    return (
      <AnimatedRect
        x={x}
        width={BAR_WIDTH}
        rx={BAR_RX}
        fill={fill}
        animatedProps={animatedProps}
      />
    );
  },
);
