import { useEffect, useRef, useState } from "react";

import VideoPlayer from "./VideoPlayer";
import type { IAttachmentResponse } from "../../api/Attachments";
import { get } from "../../request";
import type Player from "video.js/dist/types/player";

interface IWidget {
  fileName?: string;
  fileId?: string;
  src?: string;
  type?: string;
}
const VideoWidget = ({ fileId, src, type }: IWidget) => {
  const playerRef = useRef<Player | null>(null);
  const [urlFetch, setUrlFetch] = useState<string>("");

  useEffect(() => {
    if (fileId) {
      const url = `/api/v2/attachment/${fileId}`;
      console.info("VideoWidget api request", url);
      get<IAttachmentResponse>(url).then((json) => {
        console.debug("VideoWidget api response", json);
        if (json.ok) {
          setUrlFetch(json.data.url);
        }
      });
    }
  }, [fileId]);

  const handlePlayerReady = (player: Player) => {
    if (playerRef.current) {
      playerRef.current = player;
      player.on("waiting", () => {
        console.log("player is waiting");
      });

      player.on("dispose", () => {
        console.log("player will dispose");
      });
    }
  };

  return (
    <VideoPlayer
      options={{
        autoplay: false,
        controls: true,
        responsive: true,
        fluid: true,
        poster: "",
        sources: [
          {
            src: src ?? urlFetch,
            type: type ? type : "video/mp4",
          },
        ],
      }}
      onReady={handlePlayerReady}
    />
  );
};

export default VideoWidget;
