import { useRef } from "react";
import { X } from "lucide-react";
import type { AutoplayPayload } from "@/lib/autoplay-ipc";

interface AutoplayCardContentProps {
  payload: AutoplayPayload;
  onDismiss: () => void;
  onNavigate: () => void;
  onEnded: () => void;
}

export function AutoplayCardContent({
  payload,
  onDismiss,
  onNavigate,
  onEnded,
}: AutoplayCardContentProps) {
  const mediaRef = useRef<HTMLVideoElement | HTMLAudioElement | null>(null);

  const isVideo = payload.mimeType.startsWith("video/");

  const handleClick = () => {
    mediaRef.current?.pause();
    onNavigate();
  };

  const handleClose = (e: React.MouseEvent) => {
    e.stopPropagation();
    mediaRef.current?.pause();
    onDismiss();
  };

  return (
    <div
      className="relative h-full w-full cursor-pointer overflow-hidden bg-black"
      onClick={handleClick}
    >
      {isVideo ? (
        <>
          <video
            ref={mediaRef as React.Ref<HTMLVideoElement>}
            key={payload.particleId}
            src={payload.downloadUrl}
            autoPlay
            playsInline
            onEnded={onEnded}
            className="block h-full w-full object-cover"
          />
          <button
            className="absolute top-1 right-1 z-10 rounded-full bg-black/50 p-0.5 text-white hover:bg-black/70"
            onClick={handleClose}
          >
            <X className="size-3.5" />
          </button>
          <div className="absolute inset-x-0 bottom-0 flex items-center gap-2 bg-gradient-to-t from-black/60 to-transparent px-3 py-2">
            <div className="flex size-6 shrink-0 items-center justify-center rounded-full bg-white/20 text-[10px] font-medium text-white">
              {payload.senderInitials}
            </div>
            <p className="truncate text-xs text-white/80">{payload.senderName}</p>
          </div>
        </>
      ) : (
        <>
          <button
            className="absolute top-1 right-1 z-10 rounded-full bg-black/50 p-0.5 text-white hover:bg-black/70"
            onClick={handleClose}
          >
            <X className="size-3.5" />
          </button>
          <div className="flex h-full w-full items-center gap-2 bg-card px-3 py-3">
            <div className="flex size-8 shrink-0 items-center justify-center rounded-full bg-primary/10 text-xs font-medium text-primary">
              {payload.senderInitials}
            </div>
            <div className="min-w-0 flex-1">
              <p className="truncate text-sm font-medium text-card-foreground">{payload.senderName}</p>
              <p className="text-xs text-muted-foreground">Playing audio...</p>
            </div>
          </div>
          <audio
            ref={mediaRef as React.Ref<HTMLAudioElement>}
            key={payload.particleId}
            src={payload.downloadUrl}
            autoPlay
            onEnded={onEnded}
          />
        </>
      )}
    </div>
  );
}
