"use client";

import { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { toast } from "@/components/ui/Toaster";
import { 
  Smartphone, 
  Upload as UploadIcon, 
  FileVideo, 
  X, 
  Sparkles, 
  ShieldCheck, 
  ArrowRight, 
  Loader2,
  Play,
  ArrowLeft,
  CheckCircle2
} from "lucide-react";
import Link from "next/link";
import { useSession } from "next-auth/react";

export default function ShortsUploadPage() {
  const router = useRouter();
  const { data: session } = useSession();
  
  const [categories, setCategories] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [isDragging, setIsDragging] = useState(false);
  const [legalConsent, setLegalConsent] = useState(true); // ✅ Coché par défaut pour ne pas bloquer l'utilisateur

  const fileInputRef = useRef<HTMLInputElement>(null);
  const videoRef = useRef<HTMLVideoElement>(null);
  
  const [form, setForm] = useState({
    title: "",
    description: "",
    categoryId: "",
    duration: "",
    tags: "",
  });
  
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [videoObjectUrl, setVideoObjectUrl] = useState<string | null>(null);
  const [capturedThumb, setCapturedThumb] = useState<string | null>(null);

  useEffect(() => {
    fetch("/api/admin/categories")
      .then(r => r.json())
      .then(data => {
        if (Array.isArray(data)) {
          setCategories(data);
          if (data.length > 0 && !form.categoryId) {
            setForm(prev => ({ ...prev, categoryId: data[0].id }));
          }
        }
      })
      .catch(() => {});
  }, []);

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  };

  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
  };

  const handleVideoSelect = (file: File) => {
    setSelectedFile(file);
    const cleanTitle = file.name.replace(/\.[^/.]+$/, "");
    if (!form.title) {
      setForm((prev) => ({ ...prev, title: cleanTitle }));
    }
    const url = URL.createObjectURL(file);
    setVideoObjectUrl(url);
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
    if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
      const file = e.dataTransfer.files[0];
      if (file.type.startsWith("video/")) {
        handleVideoSelect(file);
      } else {
        toast("Veuillez sélectionner un fichier vidéo valide (MP4, MOV, WEBM).", "error");
      }
    }
  };

  const captureFrameAt = (second: number) => {
    if (!videoRef.current) return;
    const video = videoRef.current;
    video.currentTime = second;
    
    video.onseeked = () => {
      const canvas = document.createElement("canvas");
      canvas.width = video.videoWidth || 480;
      canvas.height = video.videoHeight || 854;
      const ctx = canvas.getContext("2d");
      if (ctx) {
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        const dataUrl = canvas.toDataURL("image/jpeg", 0.85);
        setCapturedThumb(dataUrl);
      }
      video.onseeked = null;
    };
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!selectedFile) {
      toast("Veuillez sélectionner votre fichier vidéo Short.", "error");
      return;
    }

    const finalTitle = form.title.trim() || selectedFile.name.replace(/\.[^/.]+$/, "") || "Mon Short MTBR";

    if (!legalConsent) {
      toast("Veuillez accepter l'attestation sur l'honneur (+18) pour publier.", "error");
      return;
    }

    setLoading(true);

    try {
      const formData = new FormData();
      formData.append("file", selectedFile);
      formData.append("title", finalTitle);
      formData.append("description", form.description.trim() || "Short vidéo vertical exclusif sur MTBR.");
      formData.append("categoryId", form.categoryId || (categories[0]?.id || ""));
      formData.append("duration", form.duration || (videoRef.current?.duration ? Math.round(videoRef.current.duration).toString() : "15"));
      formData.append("tags", form.tags.trim() || "#shorts, #tiktok");
      formData.append("format", "SHORT"); // 📱 Format Short vertical
      formData.append("legalConsent", "true");

      if (capturedThumb) {
        formData.append("capturedThumbData", capturedThumb);
      }

      const res = await fetch("/api/upload", {
        method: "POST",
        body: formData,
      });

      const data = await res.json().catch(() => ({ error: "Réponse serveur invalide" }));

      if (!res.ok) {
        throw new Error(data.error || `Erreur serveur (${res.status})`);
      }

      toast("Vidéo Short publiée avec succès dans le Feed Shorts !", "success");
      
      setTimeout(() => {
        router.push("/shorts");
        router.refresh();
      }, 800);

    } catch (err: any) {
      toast(err.message || "Une erreur est survenue lors de la publication.", "error");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-black text-white py-8 px-3 sm:px-6 relative selection:bg-pink-500 selection:text-white pb-32">
      
      {/* Glow Effects */}
      <div className="absolute top-0 left-1/2 -translate-x-1/2 w-[600px] h-[350px] bg-[radial-gradient(ellipse_at_center,_var(--tw-gradient-stops))] from-[#c93f52]/20 via-[#e05a68]/10 to-transparent blur-[120px] pointer-events-none -z-10" />

      <div className="max-w-2xl mx-auto">
        
        {/* Navigation Retour au Feed Shorts */}
        <div className="mb-5 flex items-center justify-between">
          <Link 
            href="/shorts" 
            className="text-xs font-bold text-[#aaaaaa] hover:text-white px-3.5 py-1.5 rounded-full bg-white/5 hover:bg-white/10 border border-white/10 transition-all flex items-center gap-1.5 active:scale-95"
          >
            <ArrowLeft size={14} /> Feed Shorts
          </Link>
          <span className="text-[10px] font-black uppercase tracking-wider text-[#e05a68] bg-[#e05a68]/10 border border-[#e05a68]/30 px-3 py-1 rounded-full flex items-center gap-1">
            <Smartphone size={12} /> Studio Shorts (9:16)
          </span>
        </div>

        {/* Header Title */}
        <div className="text-center mb-6">
          <div className="w-14 h-14 rounded-2xl bg-gradient-to-br from-[#c93f52] to-[#e05a68] flex items-center justify-center mx-auto mb-2.5 shadow-[0_0_30px_rgba(224,90,104,0.4)]">
            <Smartphone size={28} className="text-white" />
          </div>
          <h1 className="text-2xl sm:text-3xl font-black text-white tracking-tight">Publier un Short MTBR</h1>
          <p className="text-xs text-[#d8cbd0] mt-1 max-w-sm mx-auto">
            Partage ta vidéo courte verticale. Elle sera immédiatement diffusée dans le feed plein écran.
          </p>
        </div>

        {/* Form Container */}
        <form onSubmit={handleSubmit} className="space-y-5 bg-[#0e0917]/90 border border-[#2b1742] rounded-3xl p-5 sm:p-8 shadow-2xl backdrop-blur-xl">
          
          {/* ZONE DE SÉLECTION DU FICHIER VIDÉO */}
          <div
            onDragOver={handleDragOver}
            onDragLeave={handleDragLeave}
            onDrop={handleDrop}
            onClick={() => fileInputRef.current?.click()}
            className={`border-2 border-dashed rounded-2xl p-4 sm:p-6 text-center cursor-pointer transition-all duration-200 relative overflow-hidden group ${
              isDragging
                ? "border-pink-500 bg-pink-500/10 scale-[0.99]"
                : selectedFile
                ? "border-pink-500/50 bg-[#160d24]"
                : "border-[#3e2461] hover:border-pink-500/80 bg-[#120a1c]/60 hover:bg-[#160d24]"
            }`}
          >
            <input
              ref={fileInputRef}
              type="file"
              accept="video/mp4,video/webm,video/quicktime,video/mov,video/*"
              onChange={(e) => {
                if (e.target.files && e.target.files[0]) {
                  handleVideoSelect(e.target.files[0]);
                }
              }}
              className="hidden"
            />

            {selectedFile ? (
              <div className="space-y-3" onClick={(e) => e.stopPropagation()}>
                <div className="flex items-center justify-between p-3 rounded-xl bg-black/60 border border-white/10 text-left">
                  <div className="flex items-center gap-3 overflow-hidden">
                    <div className="w-10 h-10 rounded-lg bg-pink-500/20 text-pink-400 flex items-center justify-center shrink-0">
                      <FileVideo size={20} />
                    </div>
                    <div className="truncate">
                      <p className="text-xs font-bold text-white truncate max-w-[200px] sm:max-w-xs">{selectedFile.name}</p>
                      <p className="text-[10px] text-[#aaaaaa]">{(selectedFile.size / (1024 * 1024)).toFixed(2)} Mo</p>
                    </div>
                  </div>
                  <button
                    type="button"
                    onClick={() => {
                      setSelectedFile(null);
                      setVideoObjectUrl(null);
                      setCapturedThumb(null);
                    }}
                    className="p-1.5 rounded-lg bg-white/10 hover:bg-white/20 text-[#aaaaaa] hover:text-white transition-colors"
                  >
                    <X size={16} />
                  </button>
                </div>

                {/* Prévisualisation Vidéo 9:16 */}
                {videoObjectUrl && (
                  <div className="relative w-44 aspect-[9/16] mx-auto rounded-xl overflow-hidden border border-[#3e2461] shadow-2xl bg-black">
                    <video
                      ref={videoRef}
                      src={videoObjectUrl}
                      controls
                      playsInline
                      className="w-full h-full object-cover"
                      onLoadedMetadata={() => captureFrameAt(1)}
                    />
                  </div>
                )}
              </div>
            ) : (
              <div className="py-6 space-y-3">
                <div className="w-14 h-14 rounded-2xl bg-pink-500/20 border border-pink-500/40 flex items-center justify-center mx-auto text-pink-400">
                  <UploadIcon size={24} />
                </div>
                <h3 className="text-sm font-black text-white">
                  Glisse ta vidéo Short ici ou clique pour parcourir
                </h3>
                <p className="text-[11px] text-[#aaaaaa] max-w-xs mx-auto">
                  Format vertical 9:16 recommandé (&lt; 3 min). Fichiers MP4, WEBM, MOV acceptés.
                </p>
              </div>
            )}
          </div>

          {/* CHAMPS DE MÉTADONNÉES */}
          <div className="space-y-4">
            
            {/* Titre */}
            <div>
              <label className="block text-xs font-black uppercase text-[#a38890] tracking-wider mb-1.5">
                Titre du Short <span className="text-pink-400">*</span>
              </label>
              <input
                type="text"
                value={form.title}
                onChange={(e) => setForm({ ...form, title: e.target.value })}
                placeholder="Ex: Mon premier Short TikTok #viral"
                className="w-full h-11 px-4 bg-[#140e21] border border-[#352354] focus:border-pink-500 focus:shadow-[0_0_15px_rgba(236,72,153,0.3)] rounded-xl text-xs text-white placeholder-[#777777] outline-none transition-all"
              />
            </div>

            {/* Catégorie & Tags */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div>
                <label className="block text-xs font-black uppercase text-[#a38890] tracking-wider mb-1.5">
                  Catégorie
                </label>
                <select
                  value={form.categoryId}
                  onChange={(e) => setForm({ ...form, categoryId: e.target.value })}
                  className="w-full h-11 px-3 bg-[#140e21] border border-[#352354] focus:border-pink-500 rounded-xl text-xs text-white outline-none cursor-pointer"
                >
                  <option value="">Sélectionner une catégorie...</option>
                  {categories.map((c) => (
                    <option key={c.id} value={c.id}>
                      {c.name}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-xs font-black uppercase text-[#a38890] tracking-wider mb-1.5">
                  Hashtags / Tags
                </label>
                <input
                  type="text"
                  value={form.tags}
                  onChange={(e) => setForm({ ...form, tags: e.target.value })}
                  placeholder="#shorts, #tiktok, #french"
                  className="w-full h-11 px-4 bg-[#140e21] border border-[#352354] focus:border-pink-500 rounded-xl text-xs text-white placeholder-[#777777] outline-none transition-all"
                />
              </div>
            </div>

          </div>

          {/* ⚖️ CASE À COCHER JURIDIQUE OBLIGATOIRE */}
          <div className="p-3.5 rounded-2xl bg-amber-500/10 border border-amber-500/30 text-amber-200">
            <div className="flex items-start gap-3">
              <input
                type="checkbox"
                id="legalConsentShort"
                checked={legalConsent}
                onChange={(e) => setLegalConsent(e.target.checked)}
                className="mt-0.5 w-4 h-4 rounded bg-[#140e21] border-amber-500/50 accent-pink-500 cursor-pointer shrink-0"
              />
              <label htmlFor="legalConsentShort" className="text-[11px] leading-relaxed text-amber-100 font-bold cursor-pointer select-none">
                <span className="text-amber-400 font-black uppercase tracking-wider block mb-0.5">
                  Attestation sur l'honneur (+18) :
                </span>
                "Je certifie être majeur(e), détenir tous les droits sur ce Short, et que les participants sont majeurs et consentants."
              </label>
            </div>
          </div>

          {/* BOUTON DE PUBLICATION */}
          <button
            type="submit"
            disabled={loading || !selectedFile}
            className={`w-full h-12 rounded-2xl font-black text-xs flex items-center justify-center gap-2 transition-all shadow-[0_0_25px_rgba(224,90,104,0.4)] cursor-pointer ${
              !selectedFile || loading
                ? "bg-white/10 text-white/40 border border-white/5 cursor-not-allowed shadow-none"
                : "bg-gradient-to-r from-[#5c1922] via-[#c93f52] to-[#e05a68] text-white hover:opacity-95 hover:scale-[1.01] active:scale-[0.99]"
            }`}
          >
            {loading ? (
              <>
                <Loader2 className="animate-spin" size={16} />
                <span>Publication du Short en cours...</span>
              </>
            ) : (
              <>
                <span>Publier dans le Feed Shorts 📱</span>
                <ArrowRight size={16} />
              </>
            )}
          </button>

        </form>

      </div>
    </div>
  );
}
