import { useEffect, useRef, useState } from "react";
import type { Particle } from "@/api/types";
import { useDownloadUrl } from "@/hooks/use-download-url";
import { Skeleton } from "@/components/ui/skeleton";
import { AudioLevelBars } from "@/components/audio/audio-level-bars";
import { useAudioSource } from "@/components/audio/use-audio-source";

type MediaParticle = Extract<Particle, { type: "media" }>;

interface MediaParticleViewProps {
  particle: MediaParticle;
  paused: boolean;
  onEnded: () => void;
  onProgress?: (ratio: number) => void;
}

export function MediaParticleView({
  particle,
  paused,
  onEnded,
  onProgress,
}: MediaParticleViewProps) {
  const { data: url, error } = useDownloadUrl(particle.properties.object_id);

  const videoRef = useRef<HTMLVideoElement>(null);
  const audioRef = useRef<HTMLAudioElement>(null);
  const isAudio = particle.properties.mime_type?.startsWith("audio/");

  // WORKAROUND: useAudioSource needs an audio element, but audioRef is only set after mount
  const [audioEl, setAudioEl] = useState<HTMLAudioElement | null>(null);
  const audioSource = useAudioSource(audioEl);

  useEffect(() => {
    const el = isAudio ? audioRef.current : videoRef.current;
    if (!el) return;

    if (paused) {
      el.pause();
    } else {
      el.play().catch(() => {
        console.warn("Playback failed", { particleId: particle.id });
      });
    }
  }, [paused, isAudio, particle.id]);

  if (error) {
    return (
      <div className="text-muted-foreground flex items-center justify-center text-sm">
        Failed to load media
      </div>
    );
  }

  if (!url) {
    return <Skeleton className="h-full w-full rounded-none" />;
  }

  if (isAudio) {
    return (
      <div className="relative flex h-full w-full items-center justify-center bg-black/90">
        <audio
          ref={(el) => {
            audioRef.current = el;
            setAudioEl(el);
          }}
          crossOrigin="anonymous"
          src={url}
          autoPlay
          onEnded={onEnded}
          onTimeUpdate={(e) => {
            const { currentTime, duration } = e.currentTarget;
            if (duration > 0) onProgress?.(currentTime / duration);
          }}
        />

        {audioSource && (
          <div className="z-10 absolute bottom-15">
            <AudioLevelBars sourceNode={audioSource.sourceNode} />
          </div>
        )}
      </div>
    );
  }

  return (
    <div className="relative h-full w-full">
      <video
        ref={videoRef}
        src={url}
        autoPlay
        playsInline
        onEnded={onEnded}
        onTimeUpdate={(e) => {
          const { currentTime, duration } = e.currentTarget;
          if (duration > 0) onProgress?.(currentTime / duration);
        }}
        className="h-full w-full object-cover"
      />
    </div>
  );
}
