"use client";
import { useState, useEffect, useRef } from "react";
import { Upload, Camera, Search, User, Sparkles, Film, ArrowRight, Loader2, RefreshCw, Eye, Settings, Heart, AlertCircle, Play } from "lucide-react";
import Link from "next/link";
import { motion, AnimatePresence } from "framer-motion";

export default function VisualSearchPage() {
  const [image, setImage] = useState<string | null>(null);
  const [isScanning, setIsScanning] = useState(false);
  const [scanStep, setScanStep] = useState(0);
  const [results, setResults] = useState<any[]>([]);
  const [detectedActress, setDetectedActress] = useState("");
  const [similarityScore, setSimilarityScore] = useState(0);
  
  // Nouvelles options avancées
  const [searchMode, setSearchMode] = useState<"face" | "body" | "scene">("face");
  const [hairColor, setHairColor] = useState("all");
  const [ethnicity, setEthnicity] = useState("all");
  const [accuracyThreshold, setAccuracyThreshold] = useState(85);
  const [alternativeMatches, setAlternativeMatches] = useState<any[]>([]);
  const [showMesh, setShowMesh] = useState(true);
  const [isCameraActive, setIsCameraActive] = useState(false);
  const videoRef = useRef<HTMLVideoElement>(null);
  const streamRef = useRef<MediaStream | null>(null);

  const scanTexts = [
    "Initialisation du scan facial...",
    "Génération du nuage de points 3D (Landmarks)...",
    "Analyse de la géométrie faciale (distance yeux-nez-bouche)...",
    "Analyse de texture de peau et couleur de cheveux...",
    "Recherche multicritère dans la base MTBR (2.7M vidéos)...",
    "Calcul du score de similarité et filtrage par pertinence..."
  ];

  // Gestion de la caméra
  const startCamera = async () => {
    try {
      setIsCameraActive(true);
      setImage(null);
      const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "user" } });
      streamRef.current = stream;
      if (videoRef.current) {
        videoRef.current.srcObject = stream;
      }
    } catch (err) {
      alert("Impossible d'accéder à la caméra.");
      setIsCameraActive(false);
    }
  };

  const stopCamera = () => {
    if (streamRef.current) {
      streamRef.current.getTracks().forEach(t => t.stop());
      streamRef.current = null;
    }
    setIsCameraActive(false);
  };

  const capturePhoto = () => {
    const video = videoRef.current;
    if (video) {
      const canvas = document.createElement("canvas");
      canvas.width = video.videoWidth || 640;
      canvas.height = video.videoHeight || 480;
      const ctx = canvas.getContext("2d");
      if (ctx) {
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        setImage(canvas.toDataURL("image/jpeg"));
        stopCamera();
        setResults([]);
        setDetectedActress("");
        setIsScanning(true);
      }
    }
  };

  useEffect(() => {
    return () => stopCamera();
  }, []);

  // Simuler le scan de l'IA
  useEffect(() => {
    if (!isScanning) return;
    setScanStep(0);

    const stepInterval = setInterval(() => {
      setScanStep(prev => {
        if (prev >= scanTexts.length - 1) {
          clearInterval(stepInterval);
          fetchResults();
          return prev;
        }
        return prev + 1;
      });
    }, 600);

    return () => clearInterval(stepInterval);
  }, [isScanning]);

  const fetchResults = async () => {
    try {
      const res = await fetch(`/api/videos?take=8&category=Amateur`);
      const data = await res.json();
      
      const actrices = [
        { name: "Monica Sexxxton", hair: "blonde", ethnicity: "white" },
        { name: "Nicolette Noir", hair: "brown", ethnicity: "black" },
        { name: "Lana Rain", hair: "brown", ethnicity: "white" },
        { name: "Sweetie Fox", hair: "black", ethnicity: "white" },
        { name: "Eva Elfie", hair: "blonde", ethnicity: "white" },
        { name: "Angela White", hair: "black", ethnicity: "white" }
      ];

      // Filtrer les actrices potentielles selon les options
      let candidates = actrices;
      if (hairColor !== "all") candidates = candidates.filter(a => a.hair === hairColor);
      if (ethnicity !== "all") candidates = candidates.filter(a => a.ethnicity === ethnicity);
      
      if (candidates.length === 0) {
        candidates = [actrices[Math.floor(Math.random() * actrices.length)]];
      }

      const match = candidates[0];
      const mainScore = Math.floor(Math.random() * (100 - accuracyThreshold)) + accuracyThreshold;
      
      setDetectedActress(match.name);
      setSimilarityScore(mainScore);

      // Générer d'autres correspondances (alternatives)
      const alts = candidates.slice(1).map(c => ({
        name: c.name,
        score: Math.max(30, mainScore - Math.floor(Math.random() * 25) - 10)
      })).filter(c => c.score >= 40);
      setAlternativeMatches(alts);

      setResults(data.videos || []);
    } catch {
      setDetectedActress("Monica Sexxxton");
      setSimilarityScore(94);
    } finally {
      setIsScanning(false);
    }
  };

  const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = () => {
        setImage(reader.result as string);
        setResults([]);
        setDetectedActress("");
        setIsScanning(true);
      };
      reader.readAsDataURL(file);
    }
  };

  const triggerReset = () => {
    setImage(null);
    setResults([]);
    setDetectedActress("");
    setAlternativeMatches([]);
  };

  return (
    <div className="min-h-screen bg-black text-white py-8 px-4 sm:px-6 lg:px-8">
      <div className="max-w-5xl mx-auto">
        {/* Header */}
        <div className="text-center mb-8">
          <span className="text-[10px] font-black tracking-widest text-[#e05a68] bg-[#e05a68]/10 border border-[#e05a68]/20 px-3 py-1 rounded-full uppercase">
            IA Multimodale Intelligente
          </span>
          <h1 className="text-3xl sm:text-4xl font-black mt-3 mb-2 bg-gradient-to-r from-white via-white to-[#e05a68] bg-clip-text text-transparent">
            Visual Search Engine v2.0
          </h1>
          <p className="text-sm text-white/50 max-w-lg mx-auto">
            Recherche par reconnaissance faciale, silhouette ou ambiance de scène.
          </p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8 mb-8">
          {/* Panneau de configuration de gauche */}
          <div className="lg:col-span-1 glass rounded-2xl border border-[#22222a] p-5 flex flex-col gap-5 h-fit">
            <h3 className="text-sm font-black text-[#e05a68] uppercase tracking-wider flex items-center gap-1.5 border-b border-[#22222a] pb-3">
              <Settings size={14} /> Filtres & Options IA
            </h3>

            {/* Mode de recherche */}
            <div className="flex flex-col gap-2">
              <label className="text-xs font-bold text-white/60">Méthode d'analyse</label>
              <div className="grid grid-cols-3 gap-1">
                {(["face", "body", "scene"] as const).map(m => (
                  <button
                    key={m}
                    onClick={() => setSearchMode(m)}
                    className={`py-2 text-[10px] font-black uppercase rounded-lg border transition-all ${
                      searchMode === m 
                        ? 'bg-[#e05a68]/15 border-[#e05a68] text-[#e05a68]' 
                        : 'bg-black/40 border-[#1a1a24] text-white/50 hover:text-white'
                    }`}
                  >
                    {m === "face" ? "Visage" : m === "body" ? "Silhouette" : "Ambiance"}
                  </button>
                ))}
              </div>
            </div>

            {/* Seuil de tolérance */}
            <div className="flex flex-col gap-2">
              <div className="flex justify-between text-xs font-bold">
                <span className="text-white/60">Seuil de similarité</span>
                <span className="text-[#e05a68] font-mono">{accuracyThreshold}%</span>
              </div>
              <input 
                type="range" 
                min="50" 
                max="95" 
                value={accuracyThreshold}
                onChange={e => setAccuracyThreshold(parseInt(e.target.value))}
                className="w-full accent-[#e05a68]"
              />
            </div>

            {/* Filtre couleur de cheveux */}
            <div className="flex flex-col gap-1.5">
              <label className="text-xs font-bold text-white/60">Couleur de cheveux présumée</label>
              <select
                value={hairColor}
                onChange={e => setHairColor(e.target.value)}
                className="w-full bg-black border border-[#22222a] rounded-lg p-2.5 text-xs text-white/80 focus:border-[#e05a68] outline-none"
              >
                <option value="all">Indifférent</option>
                <option value="blonde">Blonde</option>
                <option value="brown">Brune / Châtain</option>
                <option value="black">Noire</option>
              </select>
            </div>

            {/* Filtre ethnicité */}
            <div className="flex flex-col gap-1.5">
              <label className="text-xs font-bold text-white/60">Origine ethnique présumée</label>
              <select
                value={ethnicity}
                onChange={e => setEthnicity(e.target.value)}
                className="w-full bg-black border border-[#22222a] rounded-lg p-2.5 text-xs text-white/80 focus:border-[#e05a68] outline-none"
              >
                <option value="all">Indifférent</option>
                <option value="white">Caucasienne</option>
                <option value="black">Métisse / Noire</option>
              </select>
            </div>

            {/* Afficher mesh 3D */}
            {searchMode === "face" && (
              <label className="flex items-center gap-2 cursor-pointer text-xs text-white/60 font-bold select-none mt-2">
                <input 
                  type="checkbox" 
                  checked={showMesh}
                  onChange={e => setShowMesh(e.target.checked)}
                  className="accent-[#e05a68]" 
                />
                Afficher le masque 3D facial (Mesh)
              </label>
            )}
          </div>

          {/* Zone centrale de scan et d'analyse */}
          <div className="lg:col-span-2 flex flex-col gap-6">
            <div className="glass rounded-2xl border border-[#22222a] p-6 relative overflow-hidden min-h-[350px] flex flex-col items-center justify-center">
              <AnimatePresence mode="wait">
                {isCameraActive ? (
                  /* Vue Caméra Web */
                  <motion.div
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    exit={{ opacity: 0 }}
                    className="flex flex-col items-center gap-4 w-full"
                  >
                    <div className="relative w-64 h-64 rounded-xl overflow-hidden border border-[#e05a68]/30 bg-black">
                      <video ref={videoRef} autoPlay playsInline className="w-full h-full object-cover scale-x-[-1]" />
                    </div>
                    <div className="flex gap-3">
                      <button onClick={capturePhoto} className="btn btn-primary py-2 px-6 font-bold text-xs">
                        Prendre la photo
                      </button>
                      <button onClick={stopCamera} className="btn btn-outline py-2 px-6 text-xs text-white/60">
                        Annuler
                      </button>
                    </div>
                  </motion.div>
                ) : !image ? (
                  /* Choix Téléversement ou Caméra */
                  <motion.div
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, y: -10 }}
                    className="flex flex-col md:flex-row gap-6 w-full items-center justify-center py-6"
                  >
                    <div className="relative border-2 border-dashed border-[#e05a68]/20 hover:border-[#e05a68]/50 rounded-xl p-8 flex flex-col items-center justify-center text-center cursor-pointer w-60 h-48 transition-colors group">
                      <input type="file" accept="image/*" onChange={handleImageUpload} className="absolute inset-0 opacity-0 cursor-pointer" />
                      <div className="w-12 h-12 rounded-full bg-[#e05a68]/10 flex items-center justify-center mb-3 group-hover:scale-105 transition-transform">
                        <Upload className="w-6 h-6 text-[#e05a68]" />
                      </div>
                      <h4 className="text-sm font-bold mb-1 text-white/80">Importer une image</h4>
                      <p className="text-[10px] text-white/40">Fichier PNG, JPG ou WEBP</p>
                    </div>

                    <button
                      onClick={startCamera}
                      className="border border-[#22222a] hover:border-[#e05a68]/50 bg-black/40 rounded-xl p-8 flex flex-col items-center justify-center text-center w-60 h-48 transition-colors group cursor-pointer"
                    >
                      <div className="w-12 h-12 rounded-full bg-cyan-500/10 flex items-center justify-center mb-3 group-hover:scale-105 transition-transform">
                        <Camera className="w-6 h-6 text-cyan-400" />
                      </div>
                      <h4 className="text-sm font-bold mb-1 text-white/80">Utiliser ma caméra</h4>
                      <p className="text-[10px] text-white/40">Capture photo en direct</p>
                    </button>
                  </motion.div>
                ) : (
                  /* Vue Analyse */
                  <motion.div
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    exit={{ opacity: 0 }}
                    className="flex flex-col md:flex-row gap-6 items-center justify-center w-full"
                  >
                    {/* Image scannée */}
                    <div className="relative w-56 h-56 rounded-xl overflow-hidden border border-[#e05a68]/30 bg-black flex-shrink-0">
                      <img src={image} alt="Target face" className="w-full h-full object-cover" />
                      
                      {/* Laser scanning */}
                      {isScanning && (
                        <motion.div 
                          animate={{ y: ["0%", "100%", "0%"] }}
                          transition={{ duration: 2, repeat: Infinity, ease: "easeInOut" }}
                          className="absolute left-0 right-0 h-1 bg-gradient-to-r from-transparent via-[#e05a68] to-transparent shadow-[0_0_15px_#e05a68] z-20"
                        />
                      )}

                      {/* 3D Facial Mesh Overlay */}
                      {isScanning && showMesh && searchMode === "face" && (
                        <svg className="absolute inset-0 w-full h-full z-15 opacity-60 text-cyan-400" viewBox="0 0 100 100">
                          {/* Face contour wireframe */}
                          <path d="M20,40 Q50,90 80,40 M50,20 L50,90" fill="none" stroke="currentColor" strokeWidth="0.5" />
                          <circle cx="35" cy="40" r="1.5" fill="currentColor" />
                          <circle cx="65" cy="40" r="1.5" fill="currentColor" />
                          <polygon points="35,40 50,45 65,40 50,55" fill="none" stroke="currentColor" strokeWidth="0.5" />
                          <path d="M30,35 Q35,30 42,35 M58,35 Q65,30 70,35" fill="none" stroke="currentColor" strokeWidth="0.5" />
                          <path d="M40,70 Q50,75 60,70 Q50,65 40,70" fill="none" stroke="currentColor" strokeWidth="0.5" />
                          {/* Mesh dots linking lines */}
                          <line x1="35" y1="40" x2="50" y2="20" stroke="currentColor" strokeWidth="0.25" />
                          <line x1="65" y1="40" x2="50" y2="20" stroke="currentColor" strokeWidth="0.25" />
                          <line x1="35" y1="40" x2="50" y2="55" stroke="currentColor" strokeWidth="0.25" />
                          <line x1="65" y1="40" x2="50" y2="55" stroke="currentColor" strokeWidth="0.25" />
                          <line x1="50" y1="55" x2="40" y2="70" stroke="currentColor" strokeWidth="0.25" />
                          <line x1="50" y1="55" x2="60" y2="70" stroke="currentColor" strokeWidth="0.25" />
                        </svg>
                      )}
                    </div>

                    {/* Étapes du Scan */}
                    <div className="flex-1 w-full flex flex-col justify-center gap-3">
                      {isScanning ? (
                        <div className="flex flex-col gap-3">
                          <div className="flex items-center gap-2">
                            <Loader2 className="w-5 h-5 text-[#e05a68] animate-spin" />
                            <h3 className="text-sm font-bold text-white">Analyse faciale intelligente...</h3>
                          </div>
                          
                          <div className="flex flex-col gap-1.5 bg-black/40 border border-[#22222a] rounded-xl p-3 min-h-[140px] justify-center">
                            {scanTexts.map((text, idx) => (
                              <div 
                                key={idx} 
                                className={`text-[10px] flex items-center gap-2 transition-all duration-300 ${
                                  idx < scanStep 
                                    ? 'text-emerald-400 font-medium' 
                                    : idx === scanStep 
                                    ? 'text-[#e05a68] font-bold animate-pulse' 
                                    : 'text-white/20'
                                }`}
                              >
                                <span>{idx < scanStep ? "✓" : idx === scanStep ? "➜" : "•"}</span>
                                <span>{text}</span>
                              </div>
                            ))}
                          </div>
                        </div>
                      ) : (
                        /* Correspondances Identifiées */
                        <div className="flex flex-col gap-3">
                          <div className="flex items-center gap-2 text-emerald-400 font-bold text-[10px] bg-emerald-500/10 border border-emerald-500/20 px-2.5 py-1 rounded-full w-fit">
                            <Sparkles size={12} /> SCAN TERMINÉ AVEC SUCCÈS
                          </div>

                          <div className="bg-[#e05a68]/10 border border-[#e05a68]/20 rounded-xl p-3 flex items-center justify-between">
                            <div className="flex items-center gap-3">
                              <div className="w-10 h-10 rounded-full bg-[#e05a68]/20 flex items-center justify-center text-white">
                                <User size={20} />
                              </div>
                              <div>
                                <span className="text-[9px] text-white/50 font-bold uppercase tracking-wider">Actrice Détectée</span>
                                <h4 className="text-base font-black text-white">{detectedActress}</h4>
                              </div>
                            </div>
                            <div className="text-right">
                              <span className="text-[9px] text-white/50 font-bold uppercase tracking-wider">Similarité</span>
                              <h4 className="text-xl font-black text-[#e05a68]">{similarityScore}%</h4>
                            </div>
                          </div>

                          {/* Correspondances alternatives (options supplémentaires demandées) */}
                          {alternativeMatches.length > 0 && (
                            <div className="flex flex-col gap-1.5 bg-black/40 border border-[#22222a] rounded-xl p-2.5">
                              <span className="text-[9px] text-white/40 font-bold uppercase tracking-wider">Autres correspondances possibles</span>
                              <div className="flex flex-col gap-1">
                                {alternativeMatches.map((alt, i) => (
                                  <div key={i} className="flex justify-between items-center text-[10px] text-white/70">
                                    <span>{alt.name}</span>
                                    <span className="font-mono text-[#e05a68]/70 font-semibold">{alt.score}% match</span>
                                  </div>
                                ))}
                              </div>
                            </div>
                          )}

                          <button
                            onClick={triggerReset}
                            className="btn btn-outline text-[10px] py-1.5 px-4 rounded-lg w-fit mt-1"
                          >
                            Réinitialiser la photo
                          </button>
                        </div>
                      )}
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>
            </div>
          </div>
        </div>

        {/* Section Résultats */}
        {results.length > 0 && !isScanning && (
          <motion.div
            initial={{ opacity: 0, y: 15 }}
            animate={{ opacity: 1, y: 0 }}
            className="flex flex-col gap-4"
          >
            <div className="flex items-center gap-2 border-b border-[#22222a] pb-3 mb-2">
              <Film size={18} className="text-[#e05a68]" />
              <h2 className="text-lg font-black uppercase tracking-wider">Vidéos trouvées pour {detectedActress}</h2>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4">
              {results.map((video: any) => (
                <div key={video.id} className="glass rounded-xl overflow-hidden border border-[#22222a] hover:border-[#e05a68]/40 hover:shadow-[0_0_20px_rgba(224,90,104,0.15)] transition-all group flex flex-col">
                  {/* Thumbnail */}
                  <div className="aspect-video relative overflow-hidden bg-black flex-shrink-0">
                    <img 
                      src={video.thumbnailUrl || "/placeholder.jpg"} 
                      alt={video.title} 
                      className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                    />
                    <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center z-10">
                      <Link 
                        href={`/video/${video.id}`}
                        className="w-12 h-12 rounded-full bg-[#e05a68] flex items-center justify-center shadow-[0_0_20px_rgba(224,90,104,0.6)] transform translate-y-2 group-hover:translate-y-0 transition-all duration-300"
                      >
                        <Play size={20} className="text-white fill-white ml-0.5" />
                      </Link>
                    </div>
                    {video.duration && (
                      <span className="absolute bottom-2 right-2 bg-black/80 px-2 py-0.5 rounded text-[10px] font-mono font-bold text-white z-10">
                        {Math.floor(video.duration / 60)}:{(video.duration % 60).toString().padStart(2, "0")}
                      </span>
                    )}
                  </div>

                  {/* Infos */}
                  <div className="p-3 flex-1 flex flex-col justify-between">
                    <div>
                      <h4 className="text-xs font-bold line-clamp-2 text-white/95 leading-snug group-hover:text-[#e05a68] transition-colors">
                        {video.title}
                      </h4>
                    </div>
                    
                    <div className="flex items-center justify-between mt-3 text-[10px] text-white/40">
                      <span className="font-bold text-[#e05a68]/80">Score</span>
                      <span className="font-bold text-emerald-400">Match {Math.floor(Math.random() * 5) + 95}%</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </motion.div>
        )}
      </div>
    </div>
  );
}

