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

const DEFAULT_TITLE = "No need to be discrete";

export default function FullscreenVideoTitle({
  props,
  paused,
  onMediaLoadingChange
}: SlideRuntimeProps) {
  const data = props as FullscreenVideoTitleData;
  const title = String(data.title ?? "").trim() || DEFAULT_TITLE;
  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-title ${
        paused ? "fullscreen-video-title--paused" : ""
      }`}
    >
      <video
        ref={videoRef}
        className="fullscreen-video-title__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)}
      />
      <div className="fullscreen-video-title__overlay">
        <h2 className="fullscreen-video-title__title">{title}</h2>
      </div>
    </article>
  );
}
