import {useMemo} from 'react';
import Svg from 'react-native-svg';
import {SharedValue} from 'react-native-reanimated';
import {useTheme} from '@shared/theme';

import {WaveformBar} from './components/WaveformBar';
import {BAR_STEP, CONTAINER_HEIGHT, CONTAINER_WIDTH} from '../constants';

interface Props {
  containerHeight?: number;
  maxBarHeight?: number;
  containerWidth?: number;
  normalizedBarsHeights: SharedValue<number[]>; // 0-1 normalized heights for each bar
}

export function AnimatedWaveForm({
  normalizedBarsHeights,
  containerHeight = CONTAINER_HEIGHT,
  containerWidth = CONTAINER_WIDTH,
  maxBarHeight,
}: Props) {
  const {theme} = useTheme();

  const barColor = theme.brand[400];

  const barIndices = useMemo(() => {
    const maxBars = Math.floor(containerWidth / BAR_STEP);
    return Array.from({length: maxBars}, (_, i) => i);
  }, [containerWidth]);

  return (
    <Svg width={containerWidth} height={containerHeight}>
      {barIndices.map(i => (
        <WaveformBar
          key={i}
          x={containerWidth - (i + 1) * BAR_STEP}
          // i=0 → rightmost, i=maxBars-1 → leftmost. Reads from END of array for right-anchoring.
          index={i}
          normalizedBarHeights={normalizedBarsHeights}
          fill={barColor}
          maxBarHeight={maxBarHeight}
        />
      ))}
    </Svg>
  );
}
