"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { Lock } from "lucide-react";
import { formatNumber, formatDuration } from "@/lib/utils";

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

interface Props {
  mediaId: string;
  isPremium: boolean;
}

function getCountryCode(title: string, tags?: string | null): string {
  const text = `${title} ${tags || ""}`.toLowerCase();
  if (/french|francais|francaise|français|france|paris|vostfr|vf|beurette|jacquie|michel|salope|lesbienne/.test(text)) return "fr";
  if (/japanese|japan|jav|hentai|tokyo|asian/.test(text)) return "jp";
  if (/german|deutsch|deutschland|berlin/.test(text)) return "de";
  if (/spanish|espanol|español|latina|mexican|spain|madrid/.test(text)) return "es";
  if (/italian|italiano|italiana|italy|roma/.test(text)) return "it";
  if (/russian|russia|moscow/.test(text)) return "ru";
  return "us";
}

export function RecommendedVideos({ mediaId, isPremium }: Props) {
  const [videos, setVideos] = useState<Media[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState("similar");
  const [activeCountry, setActiveCountry] = useState<string | null>(null);

  useEffect(() => {
    fetch(`/api/media/recommendations?mediaId=${mediaId}&limit=12`)
      .then((r) => r.json())
      .then((data) => {
        setVideos(Array.isArray(data) ? data : []);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, [mediaId]);

  const tabs = [
    { id: "similar", label: "🎬 Vidéos similaires" },
    { id: "trending", label: "🔥 Tendances" },
    { id: "new", label: "🕒 Nouveau" },
    { id: "top", label: "🌟 Top Modèles" },
    { id: "views", label: "👁️ Plus vues" },
    { id: "likes", label: "❤️ Plus aimées" },
    { id: "oldest", label: "📜 Anciennes" },
  ];

  const countries = [
    { code: "fr", flag: "🇫🇷", label: "France" },
    { code: "es", flag: "🇪🇸", label: "Espagne" },
    { code: "us", flag: "🇺🇸", label: "USA" },
  ];

  const filteredVideos = activeCountry 
    ? videos.filter(v => getCountryCode(v.title, v.tags) === activeCountry)
    : videos;

  if (loading) {
    return (
      <div className="space-y-4">
        {[...Array(6)].map((_, i) => (
          <div key={i} className="flex gap-3 animate-pulse">
            <div className="w-32 h-20 rounded-xl bg-[#12080b]" />
            <div className="flex-1 space-y-2 pt-1">
              <div className="h-3 bg-[#12080b] rounded w-full" />
              <div className="h-3 bg-[#12080b] rounded w-2/3" />
            </div>
          </div>
        ))}
      </div>
    );
  }

  return (
    <div className="w-full">
      {/* En-tête */}
      <div className="flex items-center justify-between gap-2 mb-4 flex-wrap pb-3 border-b border-[#2e1217]">
        <h2 className="text-lg md:text-xl font-black text-white flex items-center gap-2">
          Plus de vidéos 🎯
        </h2>
        <div className="flex items-center gap-3">
          <span className="text-xs font-bold text-[#e05a68] bg-[#e05a68]/10 border border-[#e05a68]/30 px-2.5 py-1 rounded-full flex items-center gap-1.5">
            100% française 🇫🇷
          </span>
          {/* Sélecteurs de pays */}
          <div className="flex items-center gap-1 bg-[#12080b] p-1 rounded-xl border border-[#2e1217]">
            {countries.map((c) => (
              <button
                key={c.code}
                onClick={() => setActiveCountry(activeCountry === c.code ? null : c.code)}
                className={`px-2 py-0.5 rounded-lg text-sm transition-all ${
                  activeCountry === c.code ? "bg-[#e05a68] text-white font-bold shadow" : "hover:bg-white/10"
                }`}
                title={c.label}
              >
                {c.flag}
              </button>
            ))}
            <button className="px-1.5 py-0.5 text-xs text-[#a38890] hover:text-white font-bold">
              ➕
            </button>
          </div>
        </div>
      </div>

      {/* Barre d'onglets défilante (Chips) */}
      <div className="flex items-center gap-2 overflow-x-auto scrollbar-hide pb-4 mb-4">
        {tabs.map((tab) => {
          const isActive = activeTab === tab.id;
          return (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`flex-shrink-0 px-3.5 py-1.5 rounded-full text-xs font-bold transition-all duration-300 ${
                isActive
                  ? "bg-gradient-to-r from-[#c93f52] to-[#e05a68] text-white shadow-[0_0_15px_rgba(224,90,104,0.4)] scale-105"
                  : "bg-[#12080b] border border-[#2e1217] text-[#a38890] hover:border-[#e05a68]/50 hover:text-white"
              }`}
            >
              {tab.label}
            </button>
          );
        })}
      </div>

      {/* Grille de Vidéos Responsive (3 Colonnes) */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-[20px] mb-8">
        {filteredVideos.map((v) => {
          const locked = v.isPremium && !isPremium;
          const countryCode = getCountryCode(v.title, v.tags);
          const rankNum = v.id ? (v.id.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0) % 89) + 10 : 42;

          return (
            <Link
              key={v.id}
              href={locked ? "/premium" : `/video/${v.id}`}
              className="group block select-none"
            >
              {/* Thumbnail Container 16:9 */}
              <div className="relative aspect-video bg-[#12080b] rounded-[6px] overflow-hidden mb-[10px] border border-[#2e1217] group-hover:border-[#e05a68] transition-all duration-300">
                <img
                  src={v.thumbnailUrl || "https://images.unsplash.com/photo-1616423640778-28d1b53229bd?w=800&q=80"}
                  alt={v.title}
                  className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                />

                {/* Top-Right Badge (Drapeau) */}
                <div className="absolute top-2 right-2 flex items-center justify-center w-5 h-3.5 bg-black/70 backdrop-blur-md rounded overflow-hidden border border-white/20 shadow">
                  <img 
                    src={`https://flagcdn.com/w40/${countryCode}.png`} 
                    alt="flag" 
                    className="w-full h-full object-cover" 
                  />
                </div>

                {/* Bottom-Right Badge (Timestamp) */}
                {v.duration && (
                  <span className="absolute bottom-2 right-2 bg-black/85 backdrop-blur-md text-white text-[11px] font-bold px-2 py-0.5 rounded-[4px]">
                    {formatDuration(v.duration)}
                  </span>
                )}

                {locked && (
                  <div className="absolute inset-0 flex flex-col items-center justify-center bg-black/80 backdrop-blur-sm z-10">
                    <div className="w-10 h-10 rounded-full bg-[#e05a68]/20 border border-[#e05a68] flex items-center justify-center text-[#e05a68] mb-1">
                      <Lock size={18} />
                    </div>
                    <span className="text-[10px] font-black text-[#e05a68] uppercase tracking-wider">VIP</span>
                  </div>
                )}
              </div>

              {/* Video Info Card */}
              <div className="flex gap-2.5">
                <div className="relative flex-shrink-0 mt-0.5">
                  <div className="w-8 h-8 rounded-full bg-[#12080b] border border-[#2e1217] flex items-center justify-center overflow-hidden">
                    {v.uploader?.image ? (
                      <img src={v.uploader.image} alt="avatar" className="w-full h-full object-cover" />
                    ) : (
                      <span className="text-[#e05a68] font-black text-xs">{(v.uploader?.name || v.title)[0].toUpperCase()}</span>
                    )}
                  </div>
                  <div className="absolute -bottom-1 -right-1 bg-gradient-to-r from-[#c93f52] to-[#e05a68] text-white text-[8px] font-black px-1 rounded-full border border-black shadow">
                    #{rankNum}
                  </div>
                </div>

                <div className="flex-1 min-w-0">
                  <h3 className="font-extrabold text-[13px] line-clamp-2 leading-[1.3] text-white group-hover:text-[#e05a68] transition-colors">
                    {v.title}
                  </h3>
                  <p className="text-[11px] font-bold text-[#a38890] truncate mt-0.5">
                    {v.uploader?.name || "Modèle Vérifié"}
                  </p>
                  <p className="text-[11px] text-[#a38890] mt-0.5">
                    IL Y A 7 MOIS · {formatNumber(v.views)} VUES
                  </p>
                </div>

                {/* Icône Option */}
                <button onClick={(e) => e.preventDefault()} className="text-[#a38890] hover:text-[#e05a68] p-1 shrink-0 self-start text-[16px] transition-colors">
                  ≡+
                </button>
              </div>
            </Link>
          );
        })}
      </div>
    </div>
  );
}
