"use client";

import { useEffect, useRef } from "react";
import { Film } from "lucide-react";

import { EmptyState } from "@/components/shared/empty-state";

interface VideoPlayerPreviewProps {
  src: string | null;
  posterSrc?: string;
  currentTimeSeconds?: number;
  onTimeUpdate?: (seconds: number) => void;
  onDurationAvailable?: (seconds: number) => void;
  controls?: boolean;
  muted?: boolean;
  loop?: boolean;
  className?: string;
}

export function VideoPlayerPreview({
  src,
  posterSrc,
  currentTimeSeconds,
  onTimeUpdate,
  onDurationAvailable,
  controls = true,
  muted = false,
  loop = false,
  className
}: VideoPlayerPreviewProps) {
  const videoRef = useRef<HTMLVideoElement>(null);

  useEffect(() => {
    const player = videoRef.current;
    if (!player || currentTimeSeconds === undefined || !src) {
      return;
    }

    if (Math.abs(player.currentTime - currentTimeSeconds) > 0.05) {
      player.currentTime = currentTimeSeconds;
    }
  }, [currentTimeSeconds, src]);

  if (!src) {
    return (
      <div className={className}>
        <EmptyState
          title="No Video Loaded"
          description="Upload a file to preview playback."
          icon={Film}
        />
      </div>
    );
  }

  return (
    <div className={`glass-panel panel-elevated overflow-hidden rounded-2xl border border-white/10 bg-black/70 ${className ?? ""}`}>
      <video
        ref={videoRef}
        src={src}
        poster={posterSrc}
        controls={controls}
        muted={muted}
        loop={loop}
        playsInline
        className="aspect-video w-full bg-black object-contain"
        onLoadedMetadata={(event) => {
          onDurationAvailable?.(event.currentTarget.duration);
        }}
        onTimeUpdate={(event) => {
          onTimeUpdate?.(event.currentTarget.currentTime);
        }}
      />
    </div>
  );
}
