"use client";

import { useState } from "react";
import { 
  Check, 
  Trash2, 
  Play, 
  AlertTriangle, 
  Flag, 
  ShieldBan, 
  RotateCcw, 
  Smartphone, 
  Monitor, 
  ExternalLink,
  Loader2,
  CheckCircle2,
  Hash
} from "lucide-react";
import { useRouter } from "next/navigation";
import { toast } from "@/components/ui/Toaster";
import { formatDuration } from "@/lib/utils";

export function ModerationClient({ videos }: { videos: any[] }) {
  const router = useRouter();
  const [loadingId, setLoadingId] = useState<string | null>(null);
  const [banUserMap, setBanUserMap] = useState<Record<string, boolean>>({});

  const handleAction = async (id: string, action: "restore" | "delete_ban", banUser: boolean) => {
    if (action === "delete_ban") {
      const confirmMsg = banUser
        ? "Voulez-vous vraiment supprimer cette vidéo, blacklister définitivement son hash SHA-256 et bannir l'utilisateur/IP ?"
        : "Voulez-vous vraiment supprimer cette vidéo et blacklister définitivement son hash SHA-256 ?";
      if (!confirm(confirmMsg)) return;
    }

    setLoadingId(id);
    try {
      const res = await fetch(`/api/admin/moderation/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action,
          banUser,
          reason: "Action de modération administrative",
        }),
      });

      const data = await res.json();

      if (res.ok && data.success) {
        toast(data.message || "Action effectuée avec succès", "success");
        router.refresh();
      } else {
        toast(data.error || "Erreur lors de l'action", "error");
      }
    } catch (err: any) {
      toast("Erreur réseau: " + err.message, "error");
    } finally {
      setLoadingId(null);
    }
  };

  if (videos.length === 0) {
    return (
      <div className="bg-[#12080b] border border-white/10 rounded-3xl p-12 text-center space-y-3">
        <div className="w-16 h-16 rounded-full bg-emerald-500/20 border border-emerald-500/40 flex items-center justify-center mx-auto text-emerald-400">
          <CheckCircle2 size={32} />
        </div>
        <h3 className="text-lg font-black text-white">File de modération vide</h3>
        <p className="text-xs text-[#aaaaaa] max-w-sm mx-auto">
          Toutes les vidéos signalées ont été traitées. La plateforme est propre et sécurisée.
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {videos.map((media) => {
        const isBanning = banUserMap[media.id] || false;
        const reportCount = media.reports?.length || 0;
        const isShort = media.format === "SHORT";

        return (
          <div
            key={media.id}
            className="bg-[#12080b] border border-[#2e1217] rounded-3xl p-5 sm:p-6 shadow-xl hover:border-white/20 transition-all flex flex-col lg:flex-row items-start lg:items-center justify-between gap-6"
          >
            {/* Left: Thumbnail & Info */}
            <div className="flex flex-col sm:flex-row items-start gap-4 flex-1 min-w-0">
              
              {/* Thumbnail */}
              <div className="relative w-44 sm:w-48 aspect-video rounded-2xl overflow-hidden bg-black/60 border border-white/10 shrink-0">
                {media.thumbnailUrl ? (
                  <img src={media.thumbnailUrl} alt={media.title} className="w-full h-full object-cover" />
                ) : (
                  <div className="w-full h-full flex items-center justify-center text-[#aaaaaa]">
                    <Play size={24} />
                  </div>
                )}
                
                {/* Format badge */}
                <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-white border border-white/15">
                  {isShort ? <Smartphone size={10} className="text-pink-400" /> : <Monitor size={10} className="text-[#2AABEE]" />}
                  <span>{isShort ? "Short 9:16" : "Catalogue"}</span>
                </div>

                {media.duration && (
                  <span className="absolute bottom-2 right-2 bg-black/80 backdrop-blur text-white text-[9px] font-bold px-1.5 py-0.5 rounded">
                    {formatDuration(media.duration)}
                  </span>
                )}
              </div>

              {/* Text Details */}
              <div className="space-y-1.5 min-w-0">
                <div className="flex items-center gap-2 flex-wrap">
                  <span className="text-[10px] font-black uppercase px-2.5 py-0.5 rounded-full bg-red-500/20 text-red-300 border border-red-500/40">
                    {media.status || "PENDING_REVIEW"}
                  </span>
                  
                  {reportCount > 0 && (
                    <span className="text-[10px] font-black uppercase px-2.5 py-0.5 rounded-full bg-amber-500/20 text-amber-300 border border-amber-500/40 flex items-center gap-1">
                      <Flag size={10} />
                      <span>{reportCount} signalement{reportCount > 1 ? "s" : ""}</span>
                    </span>
                  )}

                  {media.fileHash && (
                    <span className="text-[10px] font-mono text-[#aaaaaa] bg-white/5 px-2 py-0.5 rounded flex items-center gap-1 truncate max-w-[200px]" title={media.fileHash}>
                      <Hash size={10} />
                      <span>{media.fileHash.slice(0, 12)}...</span>
                    </span>
                  )}
                </div>

                <h3 className="font-black text-sm text-white leading-snug">
                  {media.title}
                </h3>

                <p className="text-xs text-[#aaaaaa] flex items-center gap-2 flex-wrap">
                  <span>Posté par : <strong className="text-white">{media.uploader?.name || media.uploader?.email || "Inconnu"}</strong></span>
                  {media.uploaderIp && <span>· IP : <strong className="font-mono text-[#e05a68]">{media.uploaderIp}</strong></span>}
                </p>

                {/* Reports summary if any */}
                {media.reports && media.reports.length > 0 && (
                  <div className="mt-2 p-3 bg-red-500/10 border border-red-500/25 rounded-xl space-y-1 text-xs">
                    <p className="font-black text-red-400 text-[11px] uppercase tracking-wider">
                      Motifs déclarés par les utilisateurs :
                    </p>
                    <div className="flex flex-wrap gap-1.5">
                      {media.reports.map((rep: any) => (
                        <span key={rep.id} className="px-2 py-0.5 rounded bg-black/40 text-white text-[10.5px] border border-white/10">
                          {rep.reason} {rep.comment ? `("${rep.comment}")` : ""}
                        </span>
                      ))}
                    </div>
                  </div>
                )}

                <div className="pt-1">
                  <a
                    href={media.url}
                    target="_blank"
                    rel="noreferrer"
                    className="inline-flex items-center gap-1 text-xs text-[#e05a68] hover:text-white font-bold transition-colors"
                  >
                    <span>Inspecter la vidéo originale</span>
                    <ExternalLink size={12} />
                  </a>
                </div>
              </div>

            </div>

            {/* Right: Actions */}
            <div className="flex flex-col sm:flex-row lg:flex-col items-stretch sm:items-center lg:items-end gap-3 w-full lg:w-auto shrink-0">
              
              {/* Option 1-clic : Bannir aussi l'utilisateur & l'IP */}
              <label className="flex items-center gap-2 p-2 bg-white/5 rounded-xl border border-white/10 cursor-pointer text-xs select-none">
                <input
                  type="checkbox"
                  checked={isBanning}
                  onChange={(e) => setBanUserMap(prev => ({ ...prev, [media.id]: e.target.checked }))}
                  className="w-4 h-4 rounded accent-red-500 cursor-pointer"
                />
                <span className="text-white/80 font-bold">Bannir le compte &amp; l'IP</span>
              </label>

              <div className="flex items-center gap-2 w-full">
                {/* Rétablir */}
                <button
                  onClick={() => handleAction(media.id, "restore", false)}
                  disabled={loadingId === media.id}
                  className="flex-1 sm:flex-none px-4 py-2.5 rounded-xl bg-emerald-500/20 hover:bg-emerald-500 hover:text-black border border-emerald-500/50 text-emerald-300 text-xs font-black transition-all flex items-center justify-center gap-1.5 cursor-pointer disabled:opacity-50"
                  title="Valider et repasser la vidéo en ACTIVE"
                >
                  <RotateCcw size={14} />
                  <span>Rétablir (Actif)</span>
                </button>

                {/* Supprimer définitivement + Ban Hash */}
                <button
                  onClick={() => handleAction(media.id, "delete_ban", isBanning)}
                  disabled={loadingId === media.id}
                  className="flex-1 sm:flex-none px-4 py-2.5 rounded-xl bg-red-600 hover:bg-red-700 text-white text-xs font-black shadow-[0_0_20px_rgba(220,38,38,0.4)] transition-all flex items-center justify-center gap-1.5 cursor-pointer disabled:opacity-50"
                  title="Supprimer la vidéo et ajouter son hash SHA-256 à la liste noire"
                >
                  {loadingId === media.id ? (
                    <Loader2 size={14} className="animate-spin" />
                  ) : (
                    <Trash2 size={14} />
                  )}
                  <span>Supprimer &amp; Blacklister</span>
                </button>
              </div>

            </div>

          </div>
        );
      })}
    </div>
  );
}

