"use client";
import { useState, useRef } from "react";
import Link from "next/link";
import { Play, Eye, Crown, BadgeCheck, ThumbsUp } from "lucide-react";
import { formatDuration, formatNumber } from "@/lib/utils";
import { Media } from "@prisma/client";

export function MediaCard({ media, showUploader = false }: { media: any; showUploader?: boolean }) {
  const [isHovered, setIsHovered] = useState(false);
  const videoRef = useRef<HTMLVideoElement>(null);
  const pressTimer = useRef<NodeJS.Timeout | null>(null);
  const isLongPress = useRef(false);

  const handleMouseEnter = () => {
    setIsHovered(true);
    if (videoRef.current) {
      videoRef.current.currentTime = 0;
      videoRef.current.play().catch(() => {});
    }
  };

  const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
    if (videoRef.current && videoRef.current.duration) {
      const rect = e.currentTarget.getBoundingClientRect();
      const pos = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
      // Scrub only if the user moves horizontally
      videoRef.current.currentTime = pos * videoRef.current.duration;
    }
  };

  const handleMouseLeave = () => {
    setIsHovered(false);
    if (videoRef.current) {
      videoRef.current.pause();
      videoRef.current.currentTime = 0;
    }
    if (pressTimer.current) clearTimeout(pressTimer.current);
  };

  const handleTouchStart = () => {
    isLongPress.current = false;
    pressTimer.current = setTimeout(() => {
      isLongPress.current = true;
      handleMouseEnter();
      // Retour haptique si supporté
      if (typeof window !== "undefined" && window.navigator && window.navigator.vibrate) {
        window.navigator.vibrate(50);
      }
    }, 400); // 400ms = long press
  };

  const handleTouchEnd = () => {
    if (pressTimer.current) clearTimeout(pressTimer.current);
    if (isLongPress.current) {
      handleMouseLeave();
    }
  };

  const handleClick = (e: React.MouseEvent) => {
    if (isLongPress.current) {
      e.preventDefault(); // Ne pas naviguer si on vient de relâcher un long press
      isLongPress.current = false;
    }
  };

  const handleContextMenu = (e: React.MouseEvent) => {
    // Bloque le menu contextuel "Ouvrir dans un nouvel onglet" natif des mobiles sur un appui long
    e.preventDefault();
  };

  // Fake satisfaction ratio based on views for demo purposes (85% to 99%)
  const ratio = 85 + (media.views % 15);

  return (
    <Link 
      href={`/video/${media.id}`} 
      className="group block select-none"
      style={{ WebkitTouchCallout: "none" }}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
      onTouchStart={handleTouchStart}
      onTouchEnd={handleTouchEnd}
      onTouchMove={handleTouchEnd}
      onClick={handleClick}
      onContextMenu={handleContextMenu}
    >
      <div 
        className="relative aspect-video bg-[#1a1a1a] rounded-lg md:rounded-xl overflow-hidden mb-2 border border-[#231400]"
        onMouseMove={handleMouseMove}
      >
        {/* Thumbnail */}
        <img
          src={media.thumbnailUrl || "https://images.unsplash.com/photo-1616423640778-28d1b53229bd?w=800&q=80"}
          alt={media.title}
          className={`absolute inset-0 w-full h-full object-cover transition-opacity duration-300 ${isHovered ? "opacity-0" : "opacity-100"}`}
        />

        {/* Video Preview (Silent) */}
        <video
          ref={videoRef}
          src={media.url}
          className={`absolute inset-0 w-full h-full object-cover transition-opacity duration-300 ${isHovered ? "opacity-100" : "opacity-0"}`}
          muted
          loop
          playsInline
        />
        
        {/* Hover overlay icon */}
        <div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center pointer-events-none backdrop-blur-[2px] z-20">
          <div className="w-16 h-16 rounded-full glass border border-white/20 flex items-center justify-center shadow-[0_0_30px_rgba(224,90,104,0.6)] transform scale-75 group-hover:scale-100 transition-transform duration-300">
            <Play size={24} className="text-white fill-white ml-1" />
          </div>
        </div>

        {/* Badges */}
        <div className="absolute bottom-2 right-2 flex gap-1.5 z-10">
          {media.isPremium && (
            <div className="bg-[#e05a68] text-black text-[9px] md:text-[10px] font-black px-1.5 py-0.5 rounded flex items-center gap-1 uppercase tracking-tight">
              VIP
            </div>
          )}
          <div className="bg-black/80 backdrop-blur-md text-white text-[9px] md:text-[10px] font-bold px-1.5 py-0.5 rounded border border-white/10">
            {formatDuration(media.duration)}
          </div>
        </div>
      </div>
      
      <div className="flex gap-2.5">
        {showUploader && media.uploader && (
          <div className="w-8 h-8 rounded-full overflow-hidden shrink-0 bg-[#12080b] mt-0.5 border border-[#2e1217]">
            {media.uploader.image ? (
              <img src={media.uploader.image} alt="uploader" className="w-full h-full object-cover" />
            ) : (
              <div className="w-full h-full flex items-center justify-center text-xs font-bold text-[#e05a68]">
                {media.uploader.name?.[0]?.toUpperCase() || "U"}
              </div>
            )}
          </div>
        )}
        <div className="flex-1 min-w-0">
          <h3 className="font-bold text-[13px] md:text-sm line-clamp-1 md:line-clamp-2 leading-snug text-white group-hover:text-[#e05a68] transition-colors" title={media.title}>
            {media.title}
          </h3>
          <div className="flex items-center gap-2 mt-1 text-[11px] text-[#aaaaaa] font-medium">
            {showUploader && media.uploader && (
              <span className="hover:text-white transition-colors flex items-center gap-1 truncate">
                {media.uploader.name}
                {media.uploader.isVerified && <BadgeCheck size={12} className="text-[#e05a68] shrink-0" fill="currentColor" />}
              </span>
            )}
            <span className="flex items-center gap-1 text-[#aaaaaa]">
              <ThumbsUp size={10} className={ratio >= 90 ? "text-emerald-400" : "text-amber-400"} /> 
              <span className={ratio >= 90 ? "text-emerald-400 font-bold" : "text-amber-400 font-bold"}>{ratio}%</span> 
              <span className="opacity-70">({formatNumber(media.views)})</span>
            </span>
          </div>
        </div>
      </div>
    </Link>
  );
}

