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

export default function FullscreenVideo({
  props,
  paused,
  onMediaLoadingChange
}: SlideRuntimeProps) {
  const data = props as FullscreenVideoData;
  const header = String(data.header ?? "").trim();
  const caption = String(data.caption ?? "").trim();
  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={`fullscreen-video ${paused ? "fullscreen-video--paused" : ""}`}
    >
      <video
        ref={videoRef}
        className="fullscreen-video__media"
        src={videoSrc}
        poster={posterSrc || undefined}
        autoPlay
        playsInline
        preload="metadata"
        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)}
      />
      {header ? (
        <div className="fullscreen-video__chrome">
          <p className="fullscreen-video__header">{header}</p>
        </div>
      ) : null}
      {caption ? <p className="fullscreen-video__caption">{caption}</p> : null}
    </article>
  );
}
