"use client";

import { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { toast } from "@/components/ui/Toaster";
import { 
  Upload as UploadIcon, 
  Video, 
  CheckCircle2, 
  Smartphone, 
  Monitor, 
  FileVideo, 
  X, 
  Image as ImageIcon, 
  Sparkles, 
  ShieldAlert, 
  Lock,
  ArrowRight,
  Loader2
} from "lucide-react";
import { useSession } from "next-auth/react";

export default function UploadPage() {
  const router = useRouter();
  const { data: session, status } = useSession();
  
  const [categories, setCategories] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);
  const [isDragging, setIsDragging] = useState(false);
  
  // Format selection : "SHORT" (TikTok) ou "LONG" (Catalogue)
  const [format, setFormat] = useState<"SHORT" | "LONG">("LONG");
  
  // Case à cocher juridique obligatoire (pré-cochée par défaut)
  const [legalConsent, setLegalConsent] = useState(true);

  const fileInputRef = useRef<HTMLInputElement>(null);
  const thumbInputRef = 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 [selectedThumbFile, setSelectedThumbFile] = useState<File | null>(null);
  const [thumbPreview, setThumbPreview] = useState<string | 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(setCategories).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);
    if (!form.title) {
      setForm((prev) => ({ ...prev, title: file.name.replace(/\.[^/.]+$/, "") }));
    }
    
    // Créer une URL temporaire pour la prévisualisation et détection automatique
    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.", "error");
      }
    }
  };

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      handleVideoSelect(e.target.files[0]);
    }
  };

  const handleThumbSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      const file = e.target.files[0];
      if (file.type.startsWith("image/")) {
        setSelectedThumbFile(file);
        setThumbPreview(URL.createObjectURL(file));
        setCapturedThumb(null);
      } else {
        toast("Veuillez sélectionner un fichier image valide.", "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 || 640;
      canvas.height = video.videoHeight || 360;
      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);
        setThumbPreview(dataUrl);
        setSelectedThumbFile(null);
        toast("Miniature capturée avec succès !", "success");
      }
      video.onseeked = null;
    };
  };

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

    if (!form.title.trim()) {
      toast("Le titre de la vidéo est obligatoire.", "error");
      return;
    }

    if (!legalConsent) {
      toast("L'attestation juridique et le consentement légal (+18) sont obligatoires.", "error");
      return;
    }

    setLoading(true);

    try {
      const formData = new FormData();
      formData.append("file", selectedFile);
      formData.append("title", form.title.trim());
      formData.append("description", form.description.trim());
      formData.append("categoryId", form.categoryId);
      formData.append("duration", form.duration || (videoRef.current?.duration ? Math.round(videoRef.current.duration).toString() : "0"));
      formData.append("tags", form.tags.trim());
      formData.append("format", format);
      formData.append("legalConsent", "true");

      if (selectedThumbFile) {
        formData.append("thumbnailFile", selectedThumbFile);
      } else 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})`);
      }

      setSuccess(true);
      toast(
        format === "SHORT" 
          ? "Vidéo Short publiée avec succès dans le Feed !" 
          : "Vidéo publiée avec succès dans le Catalogue !", 
        "success"
      );
      
      setTimeout(() => {
        router.push(format === "SHORT" ? "/shorts" : `/video/${data.id}`);
      }, 1500);

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

  if (status === "loading") {
    return (
      <div className="min-h-screen flex items-center justify-center bg-black text-white">
        <Loader2 className="animate-spin text-[#e05a68]" size={32} />
      </div>
    );
  }

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

      <div className="max-w-4xl mx-auto">
        
        {/* Header */}
        <div className="mb-8">
          <div className="flex items-center gap-2 mb-1">
            <span className="text-xs font-black uppercase tracking-wider text-[#e05a68] bg-[#e05a68]/10 border border-[#e05a68]/30 px-3 py-0.5 rounded-full">
              Studio Créateur
            </span>
          </div>
          <h1 className="text-3xl font-black tracking-tight text-white">Publier une Vidéo</h1>
          <p className="text-sm text-[#aaaaaa] mt-1">
            Partage ton contenu avec la communauté MTBR (Catalogue ou Feed Shorts)
          </p>
        </div>

        {/* 📱 / 🖥️ SELECTEUR DE FORMAT */}
        <div className="mb-8 p-1.5 bg-[#12080b] border border-[#2e1217] rounded-3xl grid grid-cols-1 sm:grid-cols-2 gap-2 shadow-[0_0_30px_rgba(0,0,0,0.5)]">
          
          {/* Format Short */}
          <button
            type="button"
            onClick={() => setFormat("SHORT")}
            className={`p-4 sm:p-5 rounded-2xl flex items-center gap-4 transition-all text-left cursor-pointer ${
              format === "SHORT"
                ? "bg-gradient-to-r from-[#5c1922] to-[#c93f52] border border-[#e05a68]/60 text-white shadow-[0_0_25px_rgba(224,90,104,0.4)] scale-[1.01]"
                : "bg-transparent text-[#aaaaaa] hover:text-white hover:bg-white/5 border border-transparent"
            }`}
          >
            <div className={`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 ${
              format === "SHORT" ? "bg-white text-black" : "bg-white/10 text-white"
            }`}>
              <Smartphone size={24} />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <h3 className="font-black text-sm text-white">Vidéo Courte / Verticale (Short)</h3>
                <span className="text-[9px] font-black uppercase bg-[#e05a68]/20 text-[#e05a68] border border-[#e05a68]/40 px-2 py-0.5 rounded-full">
                  Shorts-style
                </span>
              </div>
              <p className="text-xs text-[#d8cbd0] mt-0.5">
                Format 9:16 vertical (&lt; 60s), diffusé dans le feed plein écran avec swipe.
              </p>
            </div>
          </button>

          {/* Format Long */}
          <button
            type="button"
            onClick={() => setFormat("LONG")}
            className={`p-4 sm:p-5 rounded-2xl flex items-center gap-4 transition-all text-left cursor-pointer ${
              format === "LONG"
                ? "bg-gradient-to-r from-[#5c1922] to-[#c93f52] border border-[#e05a68]/60 text-white shadow-[0_0_25px_rgba(224,90,104,0.4)] scale-[1.01]"
                : "bg-transparent text-[#aaaaaa] hover:text-white hover:bg-white/5 border border-transparent"
            }`}
          >
            <div className={`w-12 h-12 rounded-2xl flex items-center justify-center shrink-0 ${
              format === "LONG" ? "bg-white text-black" : "bg-white/10 text-white"
            }`}>
              <Monitor size={24} />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <h3 className="font-black text-sm text-white">Vidéo Longue / Horizontale</h3>
                <span className="text-[9px] font-black uppercase bg-[#2AABEE]/20 text-[#7dd3fc] border border-[#2AABEE]/40 px-2 py-0.5 rounded-full">
                  Catalogue
                </span>
              </div>
              <p className="text-xs text-[#a38890] mt-0.5">
                Format 16:9 standard, diffusé dans la grille d'accueil, catégories et recherche.
              </p>
            </div>
          </button>

        </div>

        {/* FORMULAIRE PRINCIPAL */}
        <form onSubmit={handleSubmit} className="space-y-6">
          
          {/* ZONE DRAG & DROP VIDÉO */}
          <div
            onDragOver={handleDragOver}
            onDragLeave={handleDragLeave}
            onDrop={handleDrop}
            onClick={() => !selectedFile && fileInputRef.current?.click()}
            className={`relative rounded-3xl border-2 border-dashed p-8 transition-all flex flex-col items-center justify-center text-center cursor-pointer ${
              isDragging
                ? "border-[#e05a68] bg-[#e05a68]/10 scale-[1.01]"
                : selectedFile
                ? "border-emerald-500/50 bg-emerald-950/10 cursor-default"
                : "border-white/15 bg-[#12080b] hover:border-[#e05a68]/50 hover:bg-[#180a0e]"
            }`}
          >
            <input
              type="file"
              ref={fileInputRef}
              onChange={handleFileSelect}
              accept="video/mp4,video/webm,video/mkv,video/quicktime,video/x-msvideo"
              className="hidden"
            />

            {selectedFile ? (
              <div className="w-full space-y-4">
                <div className="flex items-center justify-between p-4 rounded-2xl bg-white/5 border border-white/10">
                  <div className="flex items-center gap-3 truncate">
                    <FileVideo className="text-emerald-400 shrink-0" size={28} />
                    <div className="text-left truncate">
                      <p className="text-sm font-black text-white truncate">{selectedFile.name}</p>
                      <p className="text-xs text-[#aaaaaa]">
                        {(selectedFile.size / (1024 * 1024)).toFixed(2)} Mo
                      </p>
                    </div>
                  </div>
                  <button
                    type="button"
                    onClick={(e) => {
                      e.stopPropagation();
                      setSelectedFile(null);
                      setVideoObjectUrl(null);
                      setThumbPreview(null);
                    }}
                    className="p-2 rounded-xl bg-white/10 hover:bg-red-500/20 text-white/70 hover:text-red-400 transition-colors"
                  >
                    <X size={18} />
                  </button>
                </div>

                {/* Lecteur caché pour capture d'image */}
                {videoObjectUrl && (
                  <video
                    ref={videoRef}
                    src={videoObjectUrl}
                    className="hidden"
                    preload="metadata"
                    onLoadedMetadata={() => {
                      if (videoRef.current) {
                        const dur = Math.round(videoRef.current.duration);
                        setForm(prev => ({ ...prev, duration: dur.toString() }));
                        captureFrameAt(Math.min(2, dur / 2));
                      }
                    }}
                  />
                )}
              </div>
            ) : (
              <div className="py-6 space-y-3">
                <div className="w-16 h-16 rounded-3xl bg-[#e05a68]/20 border border-[#e05a68]/40 flex items-center justify-center mx-auto text-[#e05a68]">
                  <UploadIcon size={28} />
                </div>
                <h3 className="text-base font-black text-white">
                  Glisse ton fichier vidéo ici ou clique pour parcourir
                </h3>
                <p className="text-xs text-[#aaaaaa] max-w-sm mx-auto">
                  Prend en charge MP4, WEBM, MOV, MKV (Toutes résolutions acceptées : 1080p, 4K).
                </p>
              </div>
            )}
          </div>

          {/* METADATA FIELDS */}
          <div className="bg-[#12080b] border border-[#2e1217] rounded-3xl p-6 sm:p-7 space-y-5">
            
            {/* Titre */}
            <div>
              <label className="block text-xs font-black uppercase text-[#aaaaaa] tracking-wider mb-2">
                Titre de la vidéo <span className="text-red-400">*</span>
              </label>
              <input
                type="text"
                value={form.title}
                onChange={(e) => setForm({ ...form, title: e.target.value })}
                placeholder="Ex: Shooting Exclusif avec Clara (Full HD)"
                required
                className="w-full h-12 px-4 bg-[#180a0e] border border-[#2e1217] focus:border-[#e05a68] focus:shadow-[0_0_15px_rgba(224,90,104,0.3)] rounded-xl text-sm text-white placeholder-[#777777] outline-none transition-all"
              />
            </div>

            {/* Description */}
            <div>
              <label className="block text-xs font-black uppercase text-[#aaaaaa] tracking-wider mb-2">
                Description (facultatif)
              </label>
              <textarea
                value={form.description}
                onChange={(e) => setForm({ ...form, description: e.target.value })}
                placeholder="Détails sur la scène, les actrices/acteurs, etc."
                rows={3}
                className="w-full p-4 bg-[#180a0e] border border-[#2e1217] focus:border-[#e05a68] rounded-xl text-sm text-white placeholder-[#777777] outline-none transition-all resize-none"
              />
            </div>

            {/* Catégorie & Tags */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="block text-xs font-black uppercase text-[#aaaaaa] tracking-wider mb-2">
                  Catégorie
                </label>
                <select
                  value={form.categoryId}
                  onChange={(e) => setForm({ ...form, categoryId: e.target.value })}
                  className="w-full h-12 px-4 bg-[#180a0e] border border-[#2e1217] focus:border-[#e05a68] rounded-xl text-sm 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-[#aaaaaa] tracking-wider mb-2">
                  Tags (séparés par virgule)
                </label>
                <input
                  type="text"
                  value={form.tags}
                  onChange={(e) => setForm({ ...form, tags: e.target.value })}
                  placeholder="amateur, brunette, pov, french"
                  className="w-full h-12 px-4 bg-[#180a0e] border border-[#2e1217] focus:border-[#e05a68] rounded-xl text-sm text-white placeholder-[#777777] outline-none transition-all"
                />
              </div>
            </div>

            {/* MINIATURE / THUMBNAIL */}
            <div>
              <label className="block text-xs font-black uppercase text-[#aaaaaa] tracking-wider mb-2">
                Miniature Vidéo
              </label>
              <div className="flex items-center gap-4 flex-wrap">
                {thumbPreview && (
                  <div className="relative w-36 aspect-video rounded-xl overflow-hidden border border-white/20 shadow-md">
                    <img src={thumbPreview} alt="Aperçu" className="w-full h-full object-cover" />
                  </div>
                )}
                
                <input
                  type="file"
                  ref={thumbInputRef}
                  onChange={handleThumbSelect}
                  accept="image/*"
                  className="hidden"
                />
                
                <button
                  type="button"
                  onClick={() => thumbInputRef.current?.click()}
                  className="px-4 py-2.5 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-xs font-bold text-white flex items-center gap-2 transition-all cursor-pointer"
                >
                  <ImageIcon size={16} />
                  <span>Uploader une image personnalisée</span>
                </button>

                {videoObjectUrl && (
                  <button
                    type="button"
                    onClick={() => captureFrameAt(3)}
                    className="px-4 py-2.5 rounded-xl bg-[#e05a68]/20 hover:bg-[#e05a68]/30 border border-[#e05a68]/40 text-xs font-bold text-[#e05a68] flex items-center gap-2 transition-all cursor-pointer"
                  >
                    <Sparkles size={16} />
                    <span>Recapturer un moment</span>
                  </button>
                )}
              </div>
            </div>

          </div>

          {/* ⚖️ CASE À COCHER JURIDIQUE OBLIGATOIRE (BLOQUANTE) */}
          <div className="p-5 rounded-3xl bg-amber-500/10 border border-amber-500/30 text-amber-200">
            <div className="flex items-start gap-3">
              <input
                type="checkbox"
                id="legalConsent"
                checked={legalConsent}
                onChange={(e) => setLegalConsent(e.target.checked)}
                className="mt-1 w-5 h-5 rounded bg-[#180a0e] border-amber-500/50 accent-amber-500 cursor-pointer shrink-0"
              />
              <label htmlFor="legalConsent" className="text-xs leading-relaxed text-amber-100/90 font-bold cursor-pointer select-none">
                <span className="text-amber-400 font-black uppercase tracking-wider block mb-0.5">
                  Attestation sur l'honneur & Conformité Légale (+18) :
                </span>
                "Je certifie sur l'honneur être majeur(e) (+18), posséder l'intégralité des droits sur cette vidéo, et atteste que toutes les personnes apparaissant à l'écran sont majeures et ont donné leur consentement explicite pour sa diffusion publique."
              </label>
            </div>
          </div>

          {/* BOUTON DE SOUMISSION */}
          <button
            type="submit"
            disabled={loading || !legalConsent || !selectedFile}
            className={`w-full h-14 rounded-2xl font-black text-sm flex items-center justify-center gap-2 transition-all shadow-[0_0_30px_rgba(224,90,104,0.4)] ${
              !legalConsent || !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] hover:from-[#731f2b] hover:via-[#d64a5d] hover:to-[#eb6d7b] text-white hover:scale-[1.01] active:scale-[0.99] cursor-pointer"
            }`}
          >
            {loading ? (
              <>
                <Loader2 className="animate-spin" size={18} />
                <span>Upload et vérification de sécurité en cours...</span>
              </>
            ) : (
              <>
                <span>Publier Définitivement</span>
                <ArrowRight size={18} />
              </>
            )}
          </button>

        </form>

      </div>
    </div>
  );
}
