"use client";

import { useEffect, useState, useCallback, useRef, useMemo } from "react";
import { VideoCard } from "@/components/VideoCard";
import { InFeedVideoAdCard } from "@/components/InFeedVideoAdCard";
import { CustomInFeedAdCard, InFeedAd } from "@/components/CustomInFeedAdCard";
import { Skeleton, VideoCardSkeleton } from "@/components/Skeleton";
import { Sparkles, RefreshCw, ChevronLeft, ChevronRight, Flame, Clock, Star, Eye, Heart, History } from "lucide-react";
import { formatNumber } from "@/lib/utils";
import { motion } from "framer-motion";

const containerVariants = {
  hidden: { opacity: 0 },
  show: {
    opacity: 1,
    transition: {
      staggerChildren: 0.04
    }
  }
};

const itemVariants = {
  hidden: { opacity: 0, y: 15 },
  show: { opacity: 1, y: 0, transition: { duration: 0.25 } }
};

const PER_PAGE = 32;

interface Media {
  id: string;
  title: string;
  titleFr?: string | null;
  thumbnailUrl: string | null;
  views: number;
  isPremium: boolean;
  duration: number | null;
  category?: { name: string; slug: string } | null;
  uploader?: { name: string | null; image: string | null } | null;
}

const FILTER_PILLS = [
  { id: "trending", label: "Tendances", icon: Flame },
  { id: "new", label: "Nouveau", icon: Clock },
  { id: "top_models", label: "Top Modèles", icon: Star },
  { id: "views", label: "Plus vues", icon: Eye },
  { id: "likes", label: "Plus aimées", icon: Heart },
  { id: "old", label: "Anciennes", icon: History },
];

export function PersonalizedFeed() {
  const [videos, setVideos] = useState<Media[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(true);
  const [personalized, setPersonalized] = useState(false);
  const [seed, setSeed] = useState<number>(() => Math.floor(Date.now() / 60000));
  const [activeFilter, setActiveFilter] = useState("trending");
  const [selectedCountry, setSelectedCountry] = useState("fr");
  const [inFeedAds, setInFeedAds] = useState<InFeedAd[]>([]);
  const abortRef = useRef<AbortController | null>(null);

  useEffect(() => {
    fetch("/api/infeed-ads")
      .then((r) => r.json())
      .then((data) => {
        if (data?.ads && Array.isArray(data.ads)) {
          setInFeedAds(data.ads);
        }
      })
      .catch(() => {});
  }, []);

  const loadVideos = useCallback(async (currentPage: number, currentSeed: number, filter: string) => {
    if (abortRef.current) abortRef.current.abort();
    abortRef.current = new AbortController();

    setLoading(true);
    try {
      const recentSearches: string[] = JSON.parse(
        localStorage.getItem("recentSearches") || "[]"
      );
      const localWatched: string[] = JSON.parse(
        localStorage.getItem("localWatchHistory") || "[]"
      );

      const params = new URLSearchParams({
        page: String(currentPage),
        limit: String(PER_PAGE),
        seed: String(currentSeed || Date.now()),
        filter: filter,
        searches: recentSearches.slice(0, 30).join(","),
        watched: localWatched.slice(0, 50).join(","),
      });

      const res = await fetch(`/api/media/foryou?${params}`, {
        signal: abortRef.current.signal,
      });
      const data = await res.json();

      const vids = data.videos || [];
      setVideos(vids);
      setTotal(data.total || 0);
      setPersonalized(data.personalized || false);

    } catch (e: any) {
      if (e?.name !== "AbortError") setVideos([]);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (seed !== 0) {
      loadVideos(page, seed, activeFilter);
    }
  }, [loadVideos, seed, page, activeFilter]);

  const handleRefresh = () => {
    const newSeed = Date.now() + Math.floor(Math.random() * 100000);
    setSeed(newSeed);
    setPage(1);
    loadVideos(1, newSeed, activeFilter);
  };

  const handleFilterChange = (filterId: string) => {
    setActiveFilter(filterId);
    setPage(1);
    const newSeed = Date.now() + Math.floor(Math.random() * 100000);
    setSeed(newSeed);
    loadVideos(1, newSeed, filterId);
  };

  const handlePage = (newPage: number) => {
    if (newPage < 1 || newPage > totalPages) return;
    setPage(newPage);
    loadVideos(newPage, seed, activeFilter);
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  const totalPages = Math.max(1, Math.ceil(total / PER_PAGE));

  const getPageNumbers = () => {
    const pages: (number | string)[] = [];
    const maxVisible = 5;
    let start = Math.max(1, page - 2);
    let end = Math.min(totalPages, start + maxVisible - 1);

    if (end - start < maxVisible - 1) {
      start = Math.max(1, end - maxVisible + 1);
    }

    if (start > 1) {
      pages.push(1);
      if (start > 2) pages.push("...");
    }

    for (let i = start; i <= end; i++) {
      pages.push(i);
    }

    if (end < totalPages) {
      if (end < totalPages - 1) pages.push("...");
      pages.push(totalPages);
    }

    return pages;
  };

  const gridItems = useMemo(() => {
    const items: Array<
      | { type: "video"; data: Media; id: string }
      | { type: "custom-ad"; data: InFeedAd; id: string }
      | { type: "exoclick"; id: string }
    > = [];

    const activeAds = (inFeedAds || []).filter((a) => a.active);
    const adsByPosition = new Map<number, InFeedAd>();
    activeAds.forEach((a) => {
      adsByPosition.set(a.position, a);
    });

    let videoIdx = 0;
    let currentSlot = 1;
    const totalItems = videos.length + activeAds.length;

    while (videoIdx < videos.length && currentSlot <= totalItems + 10) {
      if (adsByPosition.has(currentSlot)) {
        const ad = adsByPosition.get(currentSlot)!;
        items.push({ type: "custom-ad", data: ad, id: `infeed-ad-${ad.id}-${currentSlot}` });
      } else {
        if (activeAds.length === 0 && currentSlot === 6) {
          items.push({ type: "exoclick", id: "exoclick-default" });
        }
        items.push({ type: "video", data: videos[videoIdx], id: videos[videoIdx].id });
        videoIdx++;
      }
      currentSlot++;
    }

    while (videoIdx < videos.length) {
      items.push({ type: "video", data: videos[videoIdx], id: videos[videoIdx].id });
      videoIdx++;
    }

    return items;
  }, [videos, inFeedAds]);

  return (
    <div>
      {/* 📌 SECTION HEADER TITRE + SOUS-TITRE (STYLE BTBF) */}
      <div className="flex flex-col md:flex-row md:items-end justify-between gap-3 mb-4">
        <div>
          <div className="flex items-center gap-2 text-xs font-bold text-[#9d4edd] mb-1">
            <span>🇫🇷 France</span>
          </div>
          <h2 className="text-xl md:text-2xl font-black text-white tracking-tight">
            En ce moment
          </h2>
        </div>
        <div className="text-right hidden md:block">
          <p className="text-xs font-black text-white/90">
            Les Meilleures Vidéos & Exclusivités du Jour – DoroHub
          </p>
          <p className="text-[11px] text-[#8a6a55]">
            Vidéos Tendances & Mises à jour 24/7
          </p>
        </div>
      </div>

      {/* 📌 BARRE DE FILTRES ET DRAPEAUX (STYLE BTBF) */}
      <div className="flex items-center gap-2 overflow-x-auto scrollbar-hide py-2 mb-5 border-b border-white/5">
        {/* Drapeaux pays */}
        <div className="flex items-center gap-1.5 pr-2.5 border-r border-white/10 shrink-0">
          {[
            { code: "fr", flag: "🇫🇷" },
            { code: "es", flag: "🇪🇸" },
            { code: "us", flag: "🇺🇸" },
          ].map(({ code, flag }) => (
            <button
              key={code}
              onClick={() => setSelectedCountry(code)}
              className={`w-7 h-7 rounded-lg flex items-center justify-center text-sm transition-all ${
                selectedCountry === code ? "bg-white/15 scale-110 shadow" : "opacity-70 hover:opacity-100"
              }`}
            >
              {flag}
            </button>
          ))}
          <button className="w-6 h-6 rounded-md bg-white/5 hover:bg-white/10 text-white/60 hover:text-white flex items-center justify-center text-xs font-black">
            +
          </button>
        </div>

        {/* Pilules de filtres */}
        <div className="flex items-center gap-2 shrink-0">
          {FILTER_PILLS.map((pill) => {
            const Icon = pill.icon;
            const isActive = activeFilter === pill.id;
            return (
              <button
                key={pill.id}
                onClick={() => handleFilterChange(pill.id)}
                className={`h-8 px-3.5 rounded-full text-xs font-extrabold flex items-center gap-1.5 transition-all shrink-0 ${
                  isActive
                    ? "bg-gradient-to-r from-[#3c096c] via-[#7b2cbf] to-[#9d4edd] text-white shadow-[0_0_15px_rgba(123,44,191,0.4)] scale-105"
                    : "bg-[#110c1c] border border-white/10 text-[#d4b09a] hover:border-[#9d4edd]/50 hover:text-white hover:bg-white/5"
                }`}
              >
                <Icon size={13} className={isActive ? "text-amber-300" : "text-[#8a6a55]"} />
                <span>{pill.label}</span>
              </button>
            );
          })}
        </div>

        {/* Bouton Mélanger à droite */}
        <button
          onClick={handleRefresh}
          className="ml-auto hidden sm:flex items-center gap-1.5 text-xs font-bold text-[#aaaaaa] hover:text-white bg-[#110c1c] hover:bg-white/10 border border-white/10 hover:border-[#9d4edd]/50 px-3 py-1.5 rounded-full transition-all shrink-0 shadow-sm"
          title="Mélanger et rafraîchir"
        >
          <RefreshCw size={12} className="text-[#9d4edd]" />
          <span>Mélanger</span>
        </button>
      </div>

      {/* Grid Vidéos */}
      {loading ? (
        <div 
          style={{ gap: "var(--custom-video-gap, 18px)" }}
          className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 mb-10"
        >
          {[...Array(12)].map((_, i) => (
            <VideoCardSkeleton key={i} />
          ))}
        </div>
      ) : (
        <motion.div 
          variants={containerVariants}
          initial="hidden"
          animate="show"
          style={{ gap: "var(--custom-video-gap, 18px)" }}
          className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 mb-10"
        >
          {gridItems.map((item) => (
            <motion.div key={item.id} variants={itemVariants}>
              {item.type === "custom-ad" ? (
                <CustomInFeedAdCard ad={item.data} />
              ) : item.type === "exoclick" ? (
                <InFeedVideoAdCard />
              ) : (
                <VideoCard media={item.data} />
              )}
            </motion.div>
          ))}
        </motion.div>
      )}

      {/* Controls de Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-center gap-2 my-12 flex-wrap">
          <button
            disabled={page === 1}
            onClick={() => handlePage(page - 1)}
            className="px-4 py-2.5 rounded-xl text-xs font-bold bg-[#110c1c] border border-white/10 text-[#aaaaaa] hover:text-white hover:border-[#9d4edd]/50 disabled:opacity-30 disabled:pointer-events-none transition-all flex items-center gap-1.5 shadow-sm"
          >
            <ChevronLeft size={16} /> Précédent
          </button>

          {getPageNumbers().map((p, idx) => (
            typeof p === "number" ? (
              <button
                key={p}
                onClick={() => handlePage(p)}
                className={`w-10 h-10 rounded-xl text-xs font-black transition-all flex items-center justify-center ${
                  page === p
                    ? "bg-gradient-to-r from-[#3c096c] via-[#7b2cbf] to-[#9d4edd] text-white shadow-[0_0_20px_rgba(123,44,191,0.4)] scale-110"
                    : "bg-[#110c1c] border border-white/10 text-[#aaaaaa] hover:border-[#9d4edd]/50 hover:text-white"
                }`}
              >
                {p}
              </button>
            ) : (
              <span key={`dots-${idx}`} className="px-2 text-[#5f5f7a] text-xs font-bold select-none">
                ...
              </span>
            )
          ))}

          <button
            disabled={page === totalPages}
            onClick={() => handlePage(page + 1)}
            className="px-4 py-2.5 rounded-xl text-xs font-bold bg-[#110c1c] border border-white/10 text-[#aaaaaa] hover:text-white hover:border-[#9d4edd]/50 disabled:opacity-30 disabled:pointer-events-none transition-all flex items-center gap-1.5 shadow-sm"
          >
            Suivant <ChevronRight size={16} />
          </button>
        </div>
      )}
    </div>
  );
}
