/* eslint-disable react-hooks/exhaustive-deps */
import React, { useEffect, useRef } from "react";
import flvjs from "flv.js";
import { Store } from "antd/es/form/interface";

const VideoPlayer = (props: Store) => {
  const videoRef = useRef<HTMLVideoElement | null>(null);
  let player: flvjs.Player | null = null;

  useEffect(() => {
    if (!props.url) return;
    if (flvjs.isSupported()) {
      const videoElement = videoRef.current;
      if (videoElement) {
        player = flvjs.createPlayer({
          type: "mp4",
          url: props.url,
        });
        player.attachMediaElement(videoElement);
        player.load();
        player.play();
      }
    }

    return () => {
      if (player) {
        player.pause();
        player.unload();
        player.detachMediaElement();
        player.destroy();
        player = null;
      }
    };
  }, [props.url]);

  return (
    <video
      ref={videoRef}
      style={{ width: "100%", height: "100%", objectFit: "cover" }}
      controls
      autoPlay
    />
  );
};

export default VideoPlayer;
