import { useEffect, useRef } from "react";
import type { SquareVideoData } from "@gnommo/slide-contracts";
import type { SlideRuntimeProps } from "../types/lecture";

export default function SquareVideo({
  props,
  paused,
  onMediaLoadingChange
}: SlideRuntimeProps) {
  const data = props as SquareVideoData;
  const videoSrc = String(data.videoSrc ?? "").trim();
  const posterSrc = String(data.posterSrc ?? "").trim();
  const videoRef = useRef<HTMLVideoElement | null>(null);

  useEffect(() => {
    const video = videoRef.current;

    if (!video) {
      return;
    }

    if (paused) {
      video.pause();
      return;
    }

    const playResult = video.play();
    if (playResult && typeof playResult.catch === "function") {
      void playResult.catch(() => {});
    }
  }, [paused, videoSrc]);

  useEffect(() => {
    if (!videoSrc) {
      onMediaLoadingChange?.(false);
      return;
    }

    onMediaLoadingChange?.(true);

    return () => {
      onMediaLoadingChange?.(false);
      const video = videoRef.current;
      if (video) {
        video.pause();
        video.currentTime = 0;
      }
    };
  }, [onMediaLoadingChange, videoSrc]);

  return (
    <article
      className={`square-video ${paused ? "square-video--paused" : ""}`}
    >
      <div className="square-video__frame">
        <video
          ref={videoRef}
          className="square-video__media"
          src={videoSrc}
          poster={posterSrc || undefined}
          autoPlay
          preload="metadata"
          playsInline
          controls={false}
          onLoadedData={() => onMediaLoadingChange?.(false)}
          onCanPlay={() => onMediaLoadingChange?.(false)}
          onPlaying={() => onMediaLoadingChange?.(false)}
          onLoadStart={() => onMediaLoadingChange?.(true)}
          onWaiting={() => onMediaLoadingChange?.(true)}
          onStalled={() => onMediaLoadingChange?.(true)}
          onSuspend={() => onMediaLoadingChange?.(false)}
          onEnded={() => onMediaLoadingChange?.(false)}
          onError={() => onMediaLoadingChange?.(false)}
        />
      </div>
    </article>
  );
}
