import { type FC, useEffect, useRef } from 'react';

import { Stack, useTheme } from '@material-hu/mui';

const BAR_WIDTH = 3;
const BAR_SPACING = 4;
const BAR_TOTAL_WIDTH = BAR_WIDTH + BAR_SPACING;

const BAR_HEIGHTS = [
  8, 8, 15, 18, 12, 13, 8, 8, 15, 18, 12, 13, 8, 8, 15, 18, 12, 13, 8, 8, 15,
  18, 12, 13,
];

type LoopingWaveProps = { isRecording: boolean };

const LoopingWave: FC<LoopingWaveProps> = props => {
  const { isRecording } = props;

  const containerRef = useRef<HTMLDivElement | null>(null);
  const animationRef = useRef<number>();
  const offsetRef = useRef(0);
  const theme = useTheme();
  const cycleWidth = BAR_HEIGHTS.length * BAR_TOTAL_WIDTH;

  useEffect(() => {
    if (!isRecording || !containerRef.current) {
      cancelAnimationFrame(animationRef.current!);
      return;
    }
    const animate = () => {
      offsetRef.current = (offsetRef.current + 0.6) % cycleWidth;
      if (containerRef.current) {
        containerRef.current.style.transform = `translateX(-${offsetRef.current}px)`;
      }
      animationRef.current = requestAnimationFrame(animate);
    };

    animationRef.current = requestAnimationFrame(animate);
    return () => cancelAnimationFrame(animationRef.current!);
  }, [isRecording]);

  return (
    <Stack
      sx={{
        overflow: 'hidden',
        height: 20,
        width: `${cycleWidth}px`,
        position: 'relative',
        mx: 0.8,
      }}
    >
      <Stack
        ref={containerRef}
        sx={{
          position: 'absolute',
          top: 0,
          left: 0,
          display: 'flex',
          flexDirection: 'row',
          alignItems: 'center',
          width: `${cycleWidth * 2}px`,
        }}
      >
        {[...BAR_HEIGHTS, ...BAR_HEIGHTS].map((height, idx) => (
          <Stack
            key={`bar_${idx}`}
            sx={{
              borderRadius: 2,
              width: `${BAR_WIDTH}px`,
              height: `${height}px`,
              mr: `${BAR_SPACING}px`,
              backgroundColor: theme.palette.new.text.neutral.lighter,
            }}
          />
        ))}
      </Stack>
    </Stack>
  );
};

export default LoopingWave;
