"use client";

import { useState } from "react";
import { 
  Smartphone, 
  Trash2, 
  Play, 
  Eye, 
  ExternalLink, 
  Loader2, 
  Plus, 
  Search, 
  Calendar,
  CheckCircle,
  Video
} from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { toast } from "@/components/ui/Toaster";
import { formatDuration, formatDate } from "@/lib/utils";

export function AdminShortsClient({ initialShorts }: { initialShorts: any[] }) {
  const router = useRouter();
  const [shorts, setShorts] = useState<any[]>(initialShorts);
  const [search, setSearch] = useState("");
  const [deletingId, setDeletingId] = useState<string | null>(null);

  const filteredShorts = shorts.filter((s) => 
    s.title.toLowerCase().includes(search.toLowerCase()) ||
    (s.uploader?.name && s.uploader.name.toLowerCase().includes(search.toLowerCase())) ||
    (s.tags && s.tags.toLowerCase().includes(search.toLowerCase()))
  );

  const handleDelete = async (id: string, title: string) => {
    if (!confirm(`Supprimer définitivement le Short "${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("Short supprimé avec succès", "success");
        setShorts(prev => prev.filter(s => s.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-6">
      
      {/* Top Controls: Search & Create */}
      <div className="flex flex-col sm:flex-row items-center justify-between gap-4 bg-[#0e0917] border border-[#26173a] p-4 rounded-2xl">
        <div className="relative w-full sm:w-80">
          <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 text-[#aaaaaa]" size={16} />
          <input
            type="text"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Rechercher un Short par titre, tag ou créateur..."
            className="w-full h-10 pl-10 pr-4 bg-[#140e21] border border-[#352354] focus:border-pink-500 rounded-xl text-xs text-white placeholder-[#777777] outline-none transition-all"
          />
        </div>

        <Link
          href="/shorts/upload"
          className="flex items-center gap-2 px-5 py-2.5 rounded-xl bg-gradient-to-r from-[#c93f52] to-[#e05a68] hover:from-pink-500 hover:to-[#8d35db] text-white text-xs font-black shadow-[0_0_20px_rgba(236,72,153,0.4)] hover:scale-105 transition-all cursor-pointer shrink-0"
        >
          <Plus size={16} />
          <span>Créer un Short 📱</span>
        </Link>
      </div>

      {filteredShorts.length === 0 ? (
        <div className="bg-[#0e0917] border border-white/10 rounded-3xl p-12 text-center space-y-3">
          <div className="w-16 h-16 rounded-full bg-pink-500/20 border border-pink-500/40 flex items-center justify-center mx-auto text-pink-400">
            <Smartphone size={32} />
          </div>
          <h3 className="text-lg font-black text-white">Aucun Short trouvé</h3>
          <p className="text-xs text-[#aaaaaa] max-w-sm mx-auto">
            {search ? "Aucun Short ne correspond à votre recherche." : "Aucune vidéo courte n'a encore été publiée sur le feed Shorts."}
          </p>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
          {filteredShorts.map((short) => {
            return (
              <div
                key={short.id}
                className="group relative bg-[#0e0917] border border-[#2b1942] hover:border-pink-500/50 rounded-2xl overflow-hidden flex flex-col transition-all duration-200 shadow-xl"
              >
                {/* Vertical Preview Container */}
                <div className="relative aspect-[9/16] bg-black overflow-hidden flex items-center justify-center">
                  {short.thumbnailUrl ? (
                    <img 
                      src={short.thumbnailUrl} 
                      alt={short.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-[#140e21]">
                      <Video size={36} className="text-pink-400/50 mb-2" />
                      <span className="text-[10px] font-bold">Vidéo Short 9:16</span>
                    </div>
                  )}

                  {/* Top Badges */}
                  <div className="absolute top-2 left-2 flex items-center gap-1 bg-black/80 backdrop-blur px-2 py-0.5 rounded-full text-[9px] font-black uppercase text-pink-300 border border-pink-500/30">
                    <Smartphone size={10} />
                    <span>Short</span>
                  </div>

                  {short.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 border border-white/10">
                      {formatDuration(short.duration)}
                    </span>
                  )}

                  {/* Overlay Play & View Link */}
                  <a
                    href={short.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-12 h-12 rounded-full bg-pink-600/90 text-white flex items-center justify-center shadow-lg transform group-hover:scale-110 transition-transform">
                      <Play size={20} className="fill-current ml-0.5" />
                    </div>
                  </a>
                </div>

                {/* Info & Admin Delete Action */}
                <div className="p-4 flex-1 flex flex-col justify-between space-y-3">
                  <div>
                    <h3 className="font-black text-xs text-white line-clamp-2 leading-snug">
                      {short.title}
                    </h3>
                    <p className="text-[11px] text-[#aaaaaa] mt-1 flex items-center justify-between">
                      <span>Par : <strong className="text-white">{short.uploader?.name || "Créateur"}</strong></span>
                      <span className="flex items-center gap-1"><Eye size={11} /> {short.views || 0}</span>
                    </p>
                  </div>

                  {short.tags && (
                    <p className="text-[10px] text-pink-400 truncate">
                      {short.tags}
                    </p>
                  )}

                  <div className="pt-2 border-t border-white/10 flex items-center justify-between gap-2">
                    <span className="text-[10px] text-[#777777] flex items-center gap-1">
                      <Calendar size={10} /> {formatDate(short.createdAt)}
                    </span>

                    {/* 🗑️ ADMIN DELETE BUTTON */}
                    <button
                      type="button"
                      onClick={() => handleDelete(short.id, short.title)}
                      disabled={deletingId === short.id}
                      className="px-3 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-[11px] font-black transition-all flex items-center gap-1.5 cursor-pointer disabled:opacity-50"
                      title="Supprimer ce short"
                    >
                      {deletingId === short.id ? (
                        <Loader2 size={12} className="animate-spin" />
                      ) : (
                        <Trash2 size={12} />
                      )}
                      <span>Supprimer</span>
                    </button>
                  </div>

                </div>

              </div>
            );
          })}
        </div>
      )}

    </div>
  );
}

