"use client";

import { useEffect, useState } from "react";

const THUMBNAIL_INTERVAL_SECONDS = 2;

export function useVideoThumbnails(
  videoUrl: string | null,
  duration: number
) {
  const [thumbnails, setThumbnails] = useState<string[]>([]);

  useEffect(() => {
    if (!videoUrl || duration <= 0) {
      setThumbnails([]);
      return;
    }

    let cancelled = false;
    const video = document.createElement("video");
    video.src = videoUrl;
    video.muted = true;
    video.playsInline = true;
    video.preload = "auto";

    const captureFrames = async () => {
      await new Promise<void>((resolve, reject) => {
        video.onloadedmetadata = () => resolve();
        video.onerror = () => reject(new Error("Failed to load video"));
      });

      const canvas = document.createElement("canvas");
      const context = canvas.getContext("2d");
      if (!context) return;

      const thumbWidth = 80;
      const thumbHeight = Math.round(
        (video.videoHeight / video.videoWidth) * thumbWidth
      );
      canvas.width = thumbWidth;
      canvas.height = thumbHeight || 45;

      const times: number[] = [];
      for (
        let t = 0;
        t < duration;
        t += THUMBNAIL_INTERVAL_SECONDS
      ) {
        times.push(t);
      }
      if (times[times.length - 1] !== duration - 0.01) {
        times.push(Math.max(0, duration - 0.05));
      }

      const results: string[] = [];

      for (const time of times) {
        if (cancelled) return;
        await new Promise<void>((resolve) => {
          video.currentTime = time;
          video.onseeked = () => resolve();
        });
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        results.push(canvas.toDataURL("image/jpeg", 0.65));
      }

      if (!cancelled) setThumbnails(results);
    };

    captureFrames().catch(() => {
      if (!cancelled) setThumbnails([]);
    });

    return () => {
      cancelled = true;
      video.removeAttribute("src");
      video.load();
    };
  }, [videoUrl, duration]);

  return thumbnails;
}
