"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { 
  User, 
  Crown, 
  Shield, 
  Smartphone, 
  Film, 
  Star, 
  History, 
  Settings, 
  Sliders, 
  Eye, 
  Trash2, 
  Plus, 
  Play, 
  LogOut, 
  Sparkles,
  Calendar,
  Clock,
  Heart,
  CheckCircle2,
  ExternalLink
} from "lucide-react";
import { signOut } from "next-auth/react";
import { formatDate, formatNumber, formatDuration } from "@/lib/utils";
import { ProfileSettingsForm } from "@/components/profile/ProfileSettingsForm";
import { ResetPreferencesButton } from "@/components/ResetPreferencesButton";
import { toast } from "@/components/ui/Toaster";

export function ProfileClient({ 
  user, 
  shorts, 
  longVideos, 
  favorites,
  history 
}: { 
  user: any; 
  shorts: any[]; 
  longVideos: any[]; 
  favorites: any[];
  history: any[]; 
}) {
  const router = useRouter();
  const [activeTab, setActiveTab] = useState<"shorts" | "videos" | "favorites" | "settings">("shorts");
  const [userShorts, setUserShorts] = useState<any[]>(shorts);
  const [userLongs, setUserLongs] = useState<any[]>(longVideos);
  const [deletingId, setDeletingId] = useState<string | null>(null);

  const isPremium = user.isPremium;
  const isAdmin = ["ADMIN", "SUPERADMIN"].includes(user.role);

  const totalViews = [...userShorts, ...userLongs].reduce((acc, curr) => acc + (curr.views || 0), 0);

  const handleDeleteMedia = async (id: string, title: string, isShort: boolean) => {
    if (!confirm(`Voulez-vous vraiment supprimer "${title}" ? Cette action est irréversible.`)) {
      return;
    }

    setDeletingId(id);
    try {
      const res = await fetch(`/api/admin/media/${id}`, { method: "DELETE" });
      const data = await res.json();
      if (res.ok && data.success) {
        toast("Vidéo supprimée avec succès", "success");
        if (isShort) {
          setUserShorts(prev => prev.filter(s => s.id !== id));
        } else {
          setUserLongs(prev => prev.filter(v => v.id !== id));
        }
        router.refresh();
      } else {
        toast(data.error || "Erreur lors de la suppression", "error");
      }
    } catch (err: any) {
      toast("Erreur réseau: " + err.message, "error");
    } finally {
      setDeletingId(null);
    }
  };

  return (
    <div className="space-y-8 animate-fade-in">
      
      {/* HERO BANNER & AVATAR CARD */}
      <div 
        className="relative overflow-hidden rounded-3xl p-6 sm:p-8 border shadow-2xl backdrop-blur-xl"
        style={{
          background: isPremium 
            ? "linear-gradient(135deg, rgba(255,179,0,0.12) 0%, rgba(224,90,104,0.2) 100%)" 
            : "linear-gradient(135deg, #12080b 0%, #1a0a0f 100%)",
          borderColor: isPremium ? "rgba(255,179,0,0.4)" : "#2e1217"
        }}
      >
        {/* Glow blur element */}
        <div className="absolute -top-24 -right-24 w-80 h-80 bg-[#e05a68]/15 rounded-full blur-[100px] pointer-events-none" />

        <div className="relative z-10 flex flex-col md:flex-row items-center justify-between gap-6">
          
          {/* User Info */}
          <div className="flex flex-col sm:flex-row items-center sm:items-start gap-5 text-center sm:text-left">
            
            {/* Avatar with Glow Ring */}
            <div className="relative">
              <div 
                className="w-24 h-24 sm:w-28 sm:h-28 rounded-full flex items-center justify-center text-4xl font-black relative overflow-hidden shadow-2xl border-4"
                style={{
                  borderColor: isPremium ? "#ffb300" : "#e05a68",
                  background: "linear-gradient(135deg, #5c1922, #c93f52)"
                }}
              >
                {user.image ? (
                  <img src={user.image} alt={user.name || "Avatar"} className="w-full h-full object-cover" />
                ) : (
                  <span className="text-white">{(user.name || user.email)?.[0]?.toUpperCase() || "M"}</span>
                )}
              </div>

              {isPremium && (
                <span className="absolute -bottom-1 -right-1 bg-amber-500 text-black p-1.5 rounded-full shadow-lg border-2 border-black" title="Membre VIP">
                  <Crown size={14} className="fill-black" />
                </span>
              )}
            </div>

            {/* Names & Badges */}
            <div className="space-y-1.5">
              <div className="flex flex-wrap items-center justify-center sm:justify-start gap-2.5">
                <h1 className="text-2xl sm:text-3xl font-black text-white tracking-tight">
                  {user.name || "Utilisateur MTBR"}
                </h1>

                {isAdmin && (
                  <span className="px-3 py-0.5 rounded-full bg-gradient-to-r from-red-600 to-[#e05a68] text-white font-black text-[10px] tracking-wider uppercase shadow-[0_0_12px_rgba(239,68,68,0.4)] flex items-center gap-1">
                    <Shield size={11} /> Admin
                  </span>
                )}

                {isPremium ? (
                  <span className="px-3 py-0.5 rounded-full bg-amber-500/20 text-amber-300 border border-amber-500/50 font-black text-[10px] tracking-wider uppercase flex items-center gap-1 shadow-[0_0_12px_rgba(255,179,0,0.3)]">
                    <Crown size={11} /> VIP Premium
                  </span>
                ) : (
                  <span className="px-2.5 py-0.5 rounded-full bg-white/10 text-[#aaaaaa] border border-white/15 font-bold text-[10px] uppercase">
                    Membre Gratuit
                  </span>
                )}
              </div>

              <p className="text-xs text-[#aaaaaa] font-medium">{user.email}</p>
              
              <p className="text-xs text-[#a38890] flex items-center justify-center sm:justify-start gap-1.5 pt-1">
                <Calendar size={13} /> Membre depuis {formatDate(user.createdAt)}
              </p>
            </div>

          </div>

          {/* Quick Actions */}
          <div className="flex flex-wrap items-center justify-center gap-3 shrink-0">
            <Link
              href="/shorts/upload"
              className="px-4 py-2.5 rounded-2xl bg-gradient-to-r from-[#c93f52] to-[#e05a68] hover:opacity-95 text-white text-xs font-black shadow-[0_0_20px_rgba(224,90,104,0.4)] hover:scale-105 transition-all flex items-center gap-1.5"
            >
              <Smartphone size={14} />
              <span>Publier un Short</span>
            </Link>

            <Link
              href="/upload"
              className="px-4 py-2.5 rounded-2xl bg-[#12080b] hover:bg-[#1a0a0f] text-white border border-[#2e1217] hover:border-[#e05a68] text-xs font-bold transition-all flex items-center gap-1.5"
            >
              <Film size={14} />
              <span>Publier Vidéo</span>
            </Link>

            {!isPremium && (
              <Link
                href="/premium"
                className="px-4 py-2.5 rounded-2xl bg-[rgba(255,179,0,0.15)] border border-[rgba(255,179,0,0.5)] text-[#ffb300] hover:bg-[rgba(255,179,0,0.25)] text-xs font-black shadow-[0_0_15px_rgba(255,179,0,0.2)] hover:scale-105 transition-all flex items-center gap-1.5"
              >
                <Crown size={14} />
                <span>Devenir VIP</span>
              </Link>
            )}
          </div>

        </div>
      </div>

      {/* STATS COUNTERS */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
        {[
          { label: "Shorts Publiés", value: userShorts.length, icon: Smartphone, color: "text-[#e05a68]" },
          { label: "Vidéos Longues", value: userLongs.length, icon: Film, color: "text-[#2AABEE]" },
          { label: "Total Vues Reçues", value: totalViews, icon: Eye, color: "text-[#00c853]" },
          { label: "Favoris Enregistrés", value: favorites.length, icon: Star, color: "text-amber-400" },
        ].map(({ label, value, icon: Icon, color }) => (
          <div 
            key={label} 
            className="bg-[#12080b] border border-[#2e1217] rounded-2xl p-4 sm:p-5 flex flex-col items-center justify-center text-center shadow-lg hover:border-white/20 transition-all"
          >
            <Icon size={22} className={`${color} mb-2`} />
            <div className="text-xl sm:text-2xl font-black text-white">{formatNumber(value)}</div>
            <p className="text-[11px] text-[#aaaaaa] font-bold mt-0.5">{label}</p>
          </div>
        ))}
      </div>

      {/* TABBED NAVIGATION */}
      <div className="flex items-center gap-2 border-b border-white/10 pb-3 overflow-x-auto scrollbar-hide">
        {[
          { id: "shorts", label: "📱 Mes Shorts", count: userShorts.length },
          { id: "videos", label: "🖥️ Mes Vidéos Longues", count: userLongs.length },
          { id: "favorites", label: "⭐ Favoris & Historique", count: favorites.length },
          { id: "settings", label: "⚙️ Paramètres du Compte", count: null },
        ].map((tab) => {
          const isActive = activeTab === tab.id;
          return (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id as any)}
              className={`px-4 py-2.5 rounded-2xl text-xs font-black transition-all flex items-center gap-2 cursor-pointer shrink-0 ${
                isActive
                  ? "bg-gradient-to-r from-[#c93f52] via-[#e05a68] to-[#f08592] text-white shadow-[0_0_20px_rgba(224,90,104,0.35)] scale-[1.02]"
                  : "bg-white/5 text-[#aaaaaa] hover:bg-white/10 hover:text-white border border-white/5"
              }`}
            >
              <span>{tab.label}</span>
              {tab.count !== null && (
                <span className={`text-[10px] px-2 py-0.2 rounded-full ${isActive ? "bg-black/30 text-white" : "bg-white/10 text-[#aaaaaa]"}`}>
                  {tab.count}
                </span>
              )}
            </button>
          );
        })}
      </div>

      {/* TAB 1: MES SHORTS */}
      {activeTab === "shorts" && (
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-black text-white flex items-center gap-2">
              <Smartphone className="text-[#e05a68]" size={20} /> Mes Vidéos Shorts (9:16)
            </h2>
            <Link
              href="/shorts/upload"
              className="text-xs font-black text-[#e05a68] hover:text-[#f08592] flex items-center gap-1"
            >
              <Plus size={14} /> Publier un nouveau Short
            </Link>
          </div>

          {userShorts.length === 0 ? (
            <div className="bg-[#12080b] border border-[#2e1217] rounded-3xl p-12 text-center space-y-4">
              <div className="w-16 h-16 rounded-full bg-[#e05a68]/15 border border-[#e05a68]/30 flex items-center justify-center mx-auto text-[#e05a68]">
                <Smartphone size={32} />
              </div>
              <h3 className="text-base font-black text-white">Vous n'avez pas encore publié de Short</h3>
              <p className="text-xs text-[#9c8e92] max-w-sm mx-auto">
                Partagez votre première vidéo courte verticale pour apparaître dans le feed Shorts MTBR.
              </p>
              <Link
                href="/shorts/upload"
                className="inline-flex items-center gap-2 px-6 py-3 rounded-2xl bg-gradient-to-r from-[#c93f52] to-[#e05a68] text-white text-xs font-black shadow-[0_0_20px_rgba(224,90,104,0.4)] hover:scale-105 transition-all"
              >
                <Plus size={16} /> Publier mon 1er Short 📱
              </Link>
            </div>
          ) : (
            <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
              {userShorts.map((s) => (
                <div 
                  key={s.id}
                  className="group relative bg-[#12080b] border border-[#2e1217] hover:border-[#e05a68]/50 rounded-2xl overflow-hidden flex flex-col transition-all shadow-xl"
                >
                  <div className="relative aspect-[9/16] bg-black overflow-hidden flex items-center justify-center">
                    {s.thumbnailUrl ? (
                      <img src={s.thumbnailUrl} alt={s.title} className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300" />
                    ) : (
                      <div className="w-full h-full flex flex-col items-center justify-center text-[#aaaaaa] bg-[#12080b]">
                        <Smartphone size={32} className="text-[#e05a68]/50 mb-1" />
                        <span className="text-[10px] font-bold">Short 9:16</span>
                      </div>
                    )}

                    {s.duration && (
                      <span className="absolute top-2 right-2 bg-black/80 backdrop-blur text-white text-[9px] font-bold px-1.5 py-0.5 rounded">
                        {formatDuration(s.duration)}
                      </span>
                    )}

                    <a 
                      href={s.url}
                      target="_blank"
                      rel="noreferrer"
                      className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 flex items-center justify-center transition-opacity"
                    >
                      <div className="w-10 h-10 rounded-full bg-[#e05a68] text-white flex items-center justify-center shadow-lg">
                        <Play size={18} className="fill-current ml-0.5" />
                      </div>
                    </a>
                  </div>

                  <div className="p-3 flex-1 flex flex-col justify-between space-y-2">
                    <div>
                      <h3 className="font-bold text-xs text-white line-clamp-2 leading-snug">{s.title}</h3>
                      <p className="text-[10px] text-[#aaaaaa] mt-1 flex items-center justify-between">
                        <span><Eye size={10} className="inline mr-1" /> {s.views || 0} vues</span>
                        <span>{formatDate(s.createdAt)}</span>
                      </p>
                    </div>

                    <button
                      type="button"
                      onClick={() => handleDeleteMedia(s.id, s.title, true)}
                      disabled={deletingId === s.id}
                      className="w-full py-1.5 rounded-lg bg-red-600/20 hover:bg-red-600 text-red-300 hover:text-white border border-red-500/40 text-[10px] font-black transition-all flex items-center justify-center gap-1 cursor-pointer disabled:opacity-50"
                    >
                      <Trash2 size={11} />
                      <span>Supprimer</span>
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* TAB 2: MES VIDÉOS LONGUES */}
      {activeTab === "videos" && (
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-black text-white flex items-center gap-2">
              <Film className="text-[#2AABEE]" size={20} /> Mes Vidéos Catalogue
            </h2>
            <Link
              href="/upload"
              className="text-xs font-black text-[#2AABEE] hover:underline flex items-center gap-1"
            >
              <Plus size={14} /> Publier une vidéo
            </Link>
          </div>

          {userLongs.length === 0 ? (
            <div className="bg-[#12080b] border border-[#2e1217] rounded-3xl p-12 text-center space-y-4">
              <div className="w-16 h-16 rounded-full bg-blue-500/20 border border-blue-500/40 flex items-center justify-center mx-auto text-blue-400">
                <Film size={32} />
              </div>
              <h3 className="text-base font-black text-white">Aucune vidéo catalogue publiée</h3>
              <p className="text-xs text-[#aaaaaa] max-w-sm mx-auto">
                Partagez des vidéos horizontales longues pour le catalogue principal.
              </p>
              <Link
                href="/upload"
                className="inline-flex items-center gap-2 px-6 py-3 rounded-2xl bg-gradient-to-r from-[#c93f52] to-[#e05a68] text-white text-xs font-black shadow-lg hover:scale-105 transition-all"
              >
                <Plus size={16} /> Publier une vidéo 🖥️
              </Link>
            </div>
          ) : (
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
              {userLongs.map((v) => (
                <div key={v.id} className="group bg-[#12080b] border border-[#2e1217] rounded-2xl overflow-hidden flex flex-col shadow-xl">
                  <div className="relative aspect-video bg-black overflow-hidden">
                    {v.thumbnailUrl ? (
                      <img src={v.thumbnailUrl} alt={v.title} className="w-full h-full object-cover group-hover:scale-105 transition-transform" />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center text-[#aaaaaa]">
                        <Film size={28} />
                      </div>
                    )}
                    {v.duration && (
                      <span className="absolute bottom-2 right-2 bg-black/80 backdrop-blur text-white text-[10px] font-bold px-1.5 py-0.5 rounded">
                        {formatDuration(v.duration)}
                      </span>
                    )}
                  </div>
                  <div className="p-3.5 flex-1 flex flex-col justify-between space-y-2">
                    <div>
                      <h3 className="font-bold text-xs text-white line-clamp-2">{v.title}</h3>
                      <p className="text-[10px] text-[#aaaaaa] mt-1">{v.views || 0} vues · {formatDate(v.createdAt)}</p>
                    </div>
                    <div className="flex items-center gap-2 pt-2 border-t border-white/10">
                      <Link href={`/video/${v.id}`} className="flex-1 py-1.5 rounded-lg bg-white/10 hover:bg-white/20 text-white text-[10px] font-bold text-center">
                        Voir
                      </Link>
                      <button
                        type="button"
                        onClick={() => handleDeleteMedia(v.id, v.title, false)}
                        disabled={deletingId === v.id}
                        className="p-1.5 rounded-lg bg-red-600/20 hover:bg-red-600 text-red-300 hover:text-white transition-all cursor-pointer"
                      >
                        <Trash2 size={13} />
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* TAB 3: FAVORIS & HISTORIQUE */}
      {activeTab === "favorites" && (
        <div className="space-y-6">
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-black text-white flex items-center gap-2">
              <Star className="text-amber-400" size={20} /> Mes Favoris Enregistrés
            </h2>
            <Link href="/favorites" className="text-xs text-amber-400 hover:underline">
              Voir tous les favoris ➔
            </Link>
          </div>

          {favorites.length === 0 ? (
            <div className="bg-[#12080b] border border-[#2e1217] rounded-2xl p-8 text-center space-y-2">
              <Star size={24} className="text-amber-400 mx-auto" />
              <p className="text-xs text-[#aaaaaa]">Aucune vidéo dans vos favoris pour le moment.</p>
            </div>
          ) : (
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
              {favorites.map((fav) => (
                <Link key={fav.id} href={`/video/${fav.media?.id || fav.mediaId}`} className="group bg-[#12080b] border border-[#2e1217] rounded-xl overflow-hidden">
                  <div className="aspect-video bg-black relative">
                    {fav.media?.thumbnailUrl && (
                      <img src={fav.media.thumbnailUrl} alt={fav.media.title} className="w-full h-full object-cover group-hover:scale-105 transition-transform" />
                    )}
                  </div>
                  <div className="p-2">
                    <p className="text-[11px] font-bold text-white line-clamp-1">{fav.media?.title || "Vidéo"}</p>
                  </div>
                </Link>
              ))}
            </div>
          )}
        </div>
      )}

      {/* TAB 4: PARAMÈTRES DU COMPTE */}
      {activeTab === "settings" && (
        <div className="space-y-6">
          <ProfileSettingsForm user={{
            name: user.name,
            email: user.email,
            image: user.image,
            isPremium: user.isPremium,
            role: user.role,
          }} />

          {/* Preferences */}
          <div className="bg-[#12080b] border border-[#2e1217] rounded-2xl p-6 space-y-3">
            <div className="flex items-center gap-2">
              <Sliders size={18} className="text-[#e05a68]" />
              <h2 className="font-bold text-sm text-white">Préférences de Recommandations</h2>
            </div>
            <p className="text-xs text-[#aaaaaa]">
              Le flux d'accueil personnalise les vidéos selon votre navigation. Réinitialisez l'historique pour repartir à zéro.
            </p>
            <ResetPreferencesButton />
          </div>
        </div>
      )}

    </div>
  );
}
