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

interface Props {
  videoUrl: string;
  onSelect: (thumbnailBlob: Blob, thumbnailUrl: string) => void;
  onCancel: () => void;
}

export default function VideoThumbnailPicker({ videoUrl, onSelect, onCancel }: Props) {
  const videoRef = useRef<HTMLVideoElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [duration, setDuration] = useState(0);
  const [currentTime, setCurrentTime] = useState(0);
  const [thumbnails, setThumbnails] = useState<string[]>([]);
  const [generating, setGenerating] = useState(true);

  // Generate thumbnail strip when video loads
  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;

    video.addEventListener("loadedmetadata", () => {
      setDuration(video.duration);
      generateThumbnails(video);
    });
  }, []);

  const generateThumbnails = async (video: HTMLVideoElement) => {
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    canvas.width = 120;
    canvas.height = 68;

    const count = Math.min(8, Math.max(4, Math.floor(video.duration / 5)));
    const interval = video.duration / count;
    const thumbs: string[] = [];

    for (let i = 0; i < count; i++) {
      const time = i * interval;
      video.currentTime = time;
      await new Promise<void>((resolve) => {
        video.onseeked = () => {
          ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
          thumbs.push(canvas.toDataURL("image/jpeg", 0.6));
          resolve();
        };
      });
    }

    setThumbnails(thumbs);
    setGenerating(false);
    // Reset to start
    video.currentTime = 0;
  };

  const seekTo = (time: number) => {
    if (videoRef.current) {
      videoRef.current.currentTime = time;
      setCurrentTime(time);
    }
  };

  const captureFrame = () => {
    const video = videoRef.current;
    const canvas = canvasRef.current;
    if (!video || !canvas) return;

    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    ctx.drawImage(video, 0, 0);
    canvas.toBlob(
      (blob) => {
        if (blob) {
          const url = URL.createObjectURL(blob);
          onSelect(blob, url);
        }
      },
      "image/jpeg",
      0.92
    );
  };

  const formatTime = (s: number) => {
    const m = Math.floor(s / 60);
    const sec = Math.floor(s % 60);
    return `${m}:${String(sec).padStart(2, "0")}`;
  };

  return (
    <div className="vr-fixed vr-inset-0 vr-z-50 vr-flex vr-items-center vr-justify-center vr-bg-black/60" onClick={onCancel}>
      <div
        className="vr-bg-white vr-rounded-xl vr-shadow-2xl vr-w-full vr-max-w-lg vr-mx-4 vr-overflow-hidden"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="vr-flex vr-items-center vr-justify-between vr-px-5 vr-py-3 vr-border-b vr-border-gray-200">
          <h3 className="vr-text-sm vr-font-bold vr-text-gray-900">Select Video Thumbnail</h3>
          <button onClick={onCancel} className="vr-text-gray-400 hover:vr-text-gray-600 vr-border-0 vr-bg-transparent vr-cursor-pointer vr-p-1">
            <i className="fa-solid fa-xmark" />
          </button>
        </div>

        {/* Video preview */}
        <div className="vr-bg-black vr-flex vr-items-center vr-justify-center" style={{ maxHeight: "300px" }}>
          <video
            ref={videoRef}
            src={videoUrl}
            className="vr-max-w-full"
            style={{ maxHeight: "300px" }}
            muted
            playsInline
            crossOrigin="anonymous"
            onTimeUpdate={() => setCurrentTime(videoRef.current?.currentTime || 0)}
          />
        </div>

        {/* Timeline scrubber */}
        <div className="vr-px-4 vr-py-3">
          <div className="vr-flex vr-items-center vr-gap-2 vr-mb-2">
            <span className="vr-text-xs vr-text-gray-500">{formatTime(currentTime)}</span>
            <input
              type="range"
              min={0}
              max={duration || 1}
              step={0.1}
              value={currentTime}
              onChange={(e) => seekTo(Number(e.target.value))}
              className="vr-flex-1"
              style={{ accentColor: "#E03058" }}
            />
            <span className="vr-text-xs vr-text-gray-500">{formatTime(duration)}</span>
          </div>

          {/* Thumbnail strip */}
          {generating ? (
            <div className="vr-flex vr-items-center vr-justify-center vr-gap-2 vr-py-3 vr-text-xs vr-text-gray-400">
              <div className="vr-w-3 vr-h-3 vr-border-2 vr-border-gray-200 vr-border-t-primary-600 vr-rounded-full vr-animate-spin" />
              Generating thumbnails...
            </div>
          ) : thumbnails.length > 0 && (
            <div className="vr-flex vr-gap-1 vr-overflow-x-auto vr-pb-1">
              {thumbnails.map((thumb, i) => (
                <button
                  key={i}
                  onClick={() => seekTo((i / thumbnails.length) * duration)}
                  className="vr-flex-shrink-0 vr-border-2 vr-border-transparent hover:vr-border-primary-600 vr-rounded vr-overflow-hidden vr-cursor-pointer vr-p-0 vr-bg-transparent vr-transition-colors"
                >
                  <img src={thumb} alt="" className="vr-w-16 vr-h-9 vr-object-cover" />
                </button>
              ))}
            </div>
          )}
        </div>

        {/* Actions */}
        <div className="vr-flex vr-items-center vr-justify-end vr-gap-2 vr-px-4 vr-py-3 vr-border-t vr-border-gray-100">
          <button onClick={onCancel} className="vr-px-4 vr-py-2 vr-text-xs vr-font-medium vr-text-gray-500 hover:vr-text-gray-700 vr-border-0 vr-bg-transparent vr-cursor-pointer">
            Cancel
          </button>
          <button
            onClick={captureFrame}
            className="vr-inline-flex vr-items-center vr-gap-1.5 vr-px-4 vr-py-2 vr-bg-primary-600 vr-text-white vr-rounded-lg vr-text-xs vr-font-semibold hover:vr-bg-primary-700 vr-transition-colors vr-border-0 vr-cursor-pointer"
          >
            <i className="fa-solid fa-camera" style={{ fontSize: "10px" }} />
            Use This Frame
          </button>
        </div>

        {/* Hidden canvas for frame capture */}
        <canvas ref={canvasRef} style={{ display: "none" }} />
      </div>
    </div>
  );
}
