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

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

const AudioVisualizer: FC = () => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const theme = useTheme();
  const strokeColor =
    theme.palette.new.action.button.background.primary.default;

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    let streamVar: MediaStream | null = null;
    const audioContext = new window.AudioContext();
    const analyser = audioContext.createAnalyser();
    const dataArray = new Uint8Array(analyser.frequencyBinCount);

    navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => {
      streamVar = stream;
      const source = audioContext.createMediaStreamSource(stream);
      source.connect(analyser);
      draw();
    });

    const draw = () => {
      requestAnimationFrame(draw);
      analyser.getByteTimeDomainData(dataArray);
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.beginPath();

      const sliceWidth = canvas.width / dataArray.length;
      let x = 0;

      for (let i = 0; i < dataArray.length; i++) {
        const normalizedValue = dataArray[i] / 128.0;
        const y = (normalizedValue * canvas.height) / 2;

        if (i === 0) {
          ctx.moveTo(x, y);
        } else {
          ctx.lineTo(x, y);
        }

        x += sliceWidth;
      }

      ctx.lineTo(canvas.width, canvas.height / 2);
      ctx.strokeStyle = strokeColor;
      ctx.stroke();
    };

    return () => {
      if (streamVar) {
        streamVar.getTracks().forEach((track: MediaStreamTrack) => {
          track.stop();
        });
      }
    };
  }, [strokeColor]);

  return (
    <Stack
      sx={{
        borderRadius: 1,
        background: theme.palette.new.background.layout.brand,
      }}
    >
      <canvas
        ref={canvasRef}
        width="100"
        height="56"
      />
    </Stack>
  );
};

export default AudioVisualizer;
