﻿"use client";
import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import { ChevronLeft, ChevronRight, Play, Crown } from "lucide-react";
import { formatDuration } from "@/lib/utils";
import { motion, AnimatePresence } from "framer-motion";

export function TrendingCarousel({ videos }: { videos: any[] }) {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [direction, setDirection] = useState(1);

  if (!videos || videos.length === 0) return null;

  const next = useCallback(() => {
    setDirection(1);
    setCurrentIndex((i) => (i + 1) % videos.length);
  }, [videos.length]);

  const prev = useCallback(() => {
    setDirection(-1);
    setCurrentIndex((i) => (i - 1 + videos.length) % videos.length);
  }, [videos.length]);

  // Auto-slide every 6 seconds
  useEffect(() => {
    const timer = setInterval(next, 6000);
    return () => clearInterval(timer);
  }, [next]);

  const currentVideo = videos[currentIndex];

  const slideVariants = {
    enter: (dir: number) => ({ x: dir > 0 ? "8%" : "-8%", opacity: 0 }),
    center: { x: 0, opacity: 1 },
    exit: (dir: number) => ({ x: dir > 0 ? "-8%" : "8%", opacity: 0 }),
  };

  return (
    <div className="relative w-full aspect-[21/9] md:aspect-[24/9] bg-black rounded-2xl overflow-hidden mb-12 group border border-[#ffffff0f] shadow-[0_24px_80px_rgba(0,0,0,0.7)]">
      
      {/* Animated background */}
      <AnimatePresence initial={false} custom={direction} mode="sync">
        <motion.div
          key={currentIndex}
          custom={direction}
          variants={slideVariants}
          initial="enter"
          animate="center"
          exit="exit"
          transition={{ duration: 0.65, ease: [0.32, 0.72, 0, 1] }}
          className="absolute inset-0"
        >
          <img
            src={currentVideo.thumbnailUrl || "https://images.unsplash.com/photo-1616423640778-28d1b53229bd?w=1600&q=80"}
            alt="Trending"
            className="w-full h-full object-cover"
          />
          {/* Multi-layer gradient for depth */}
          <div className="absolute inset-0 bg-gradient-to-t from-[#0a0a0f] via-[#0a0a0f]/70 to-transparent" />
          <div className="absolute inset-0 bg-gradient-to-r from-[#0a0a0f] via-[#0a0a0f]/40 to-transparent" />
          {/* Noise texture overlay */}
          <div className="absolute inset-0 opacity-20" style={{ backgroundImage: "url(\"data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='1'/%3E%3C/svg%3E\")" }} />
        </motion.div>
      </AnimatePresence>

      {/* Ambient glow dot */}
      <div className="absolute top-0 left-1/4 w-96 h-96 rounded-full blur-[120px] bg-[#e05a68]/20 pointer-events-none" />

      {/* Content */}
      <AnimatePresence initial={false} custom={direction} mode="sync">
        <motion.div
          key={`content-${currentIndex}`}
          custom={direction}
          variants={{
            enter: (dir: number) => ({ x: dir > 0 ? 60 : -60, opacity: 0 }),
            center: { x: 0, opacity: 1 },
            exit: { opacity: 0, transition: { duration: 0.2 } },
          }}
          initial="enter"
          animate="center"
          exit="exit"
          transition={{ duration: 0.5, ease: "easeOut", delay: 0.15 }}
          className="absolute inset-0 p-8 md:p-12 flex flex-col justify-end"
        >
          <div className="flex items-center gap-2 mb-3">
            <span className="bg-[#e05a68] text-black text-[10px] font-black px-2.5 py-1 rounded-full uppercase tracking-widest shadow-[0_0_15px_rgba(224,90,104,0.5)]">
              🔥 Tendance
            </span>
            {currentVideo.isPremium && (
              <span className="glass border border-amber-500/30 text-amber-400 text-[10px] font-black px-2.5 py-1 rounded-full flex items-center gap-1">
                <Crown size={10} /> VIP
              </span>
            )}
          </div>

          <h2 className="text-2xl md:text-4xl lg:text-5xl font-black text-white mb-4 max-w-2xl leading-tight drop-shadow-2xl line-clamp-2">
            {currentVideo.title}
          </h2>

          <div className="flex items-center gap-3 text-sm text-[#aaaaaa] mb-6 flex-wrap">
            <span className="glass px-2.5 py-1 rounded-full text-xs font-medium">{currentVideo.views?.toLocaleString()} vues</span>
            {currentVideo.duration && (
              <span className="glass px-2.5 py-1 rounded-full text-xs font-medium">{formatDuration(currentVideo.duration)}</span>
            )}
            {currentVideo.uploader && (
              <span className="text-white font-bold">by {currentVideo.uploader.name}</span>
            )}
          </div>

          <Link
            href={`/video/${currentVideo.id}`}
            className="w-fit px-7 py-3 bg-white text-black font-black rounded-xl flex items-center gap-2.5 hover:bg-[#e05a68] hover:text-black transition-all duration-200 shadow-xl hover:shadow-[0_0_30px_rgba(224,90,104,0.4)] hover:scale-105 active:scale-95"
          >
            <Play size={18} fill="currentColor" /> Regarder maintenant
          </Link>
        </motion.div>
      </AnimatePresence>

      {/* Navigation buttons */}
      <button
        onClick={prev}
        className="absolute left-4 top-1/2 -translate-y-1/2 w-10 h-10 glass border border-white/10 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all hover:bg-[#e05a68]/80 hover:border-[#e05a68] hover:scale-110 active:scale-95"
      >
        <ChevronLeft size={22} />
      </button>
      <button
        onClick={next}
        className="absolute right-4 top-1/2 -translate-y-1/2 w-10 h-10 glass border border-white/10 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all hover:bg-[#e05a68]/80 hover:border-[#e05a68] hover:scale-110 active:scale-95"
      >
        <ChevronRight size={22} />
      </button>

      {/* Dot indicators */}
      <div className="absolute bottom-5 right-8 flex gap-2 items-center">
        {videos.map((_, i) => (
          <button
            key={i}
            onClick={() => { setDirection(i > currentIndex ? 1 : -1); setCurrentIndex(i); }}
            className={`rounded-full transition-all duration-300 ${i === currentIndex ? "w-7 h-2 bg-[#e05a68] shadow-[0_0_10px_rgba(224,90,104,0.7)]" : "w-2 h-2 bg-white/25 hover:bg-white/50"}`}
          />
        ))}
      </div>

      {/* Progress bar */}
      <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-white/5">
        <motion.div
          key={currentIndex}
          className="h-full bg-[#e05a68]"
          initial={{ width: "0%" }}
          animate={{ width: "100%" }}
          transition={{ duration: 6, ease: "linear" }}
        />
      </div>
    </div>
  );
}

