import React from 'react';
import {Defs, Pattern, Rect} from 'react-native-svg';
import {SPACING, useTheme} from '@shared/theme';
import {clamp} from '@shared/utils';

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

const DEFAULT_HEIGHTS = [0.1, 0.65, 0.87, 0.54, 0.65, 0.1];

interface Props {
  color?: string;
  id?: string;
  /** Prefer this for unique `<pattern id="…">` when multiple waveforms exist (SVG ids are global). */
  patternId?: string;
  maxHeight?: number;
  normalizedBarHeights?: number[]; // 0-1 normalized heights for each bar
}

export function WaveForm({
  color,
  id,
  patternId,
  normalizedBarHeights = DEFAULT_HEIGHTS,
  maxHeight = SPACING.x3,
}: Props) {
  const {theme} = useTheme();
  const resolvedPatternId = patternId ?? id ?? 'wavePattern';
  const safeHeights =
    normalizedBarHeights.length > 0 ? normalizedBarHeights : DEFAULT_HEIGHTS;

  return (
    <Defs>
      <Pattern
        id={resolvedPatternId}
        patternUnits="userSpaceOnUse"
        width={BAR_WIDTH * safeHeights.length * 2}
        patternContentUnits={'userSpaceOnUse'}
        height={maxHeight}>
        {safeHeights.map((barHeight, index) => {
          const height = clamp(
            barHeight * maxHeight,
            MIN_BAR_HEIGHT,
            maxHeight,
          );

          return (
            <Rect
              key={index}
              x={index * BAR_WIDTH * 2}
              y={maxHeight / 2 - height / 2}
              width={BAR_WIDTH}
              height={height}
              fill={color ?? theme.icon.neutral.default}
              rx={BAR_RX}
              ry={1}
            />
          );
        })}
      </Pattern>
    </Defs>
  );
}
