"use client";
import { useState, useEffect } from "react";
import { X, Plus, Check } from "lucide-react";
import { toast } from "@/components/ui/Toaster";

export function PlaylistModal({ isOpen, onClose, mediaId }: { isOpen: boolean, onClose: () => void, mediaId: string }) {
  const [playlists, setPlaylists] = useState<any[]>([]);
  const [newPlaylistName, setNewPlaylistName] = useState("");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (isOpen) {
      fetchPlaylists();
    }
  }, [isOpen]);

  const fetchPlaylists = async () => {
    const res = await fetch("/api/playlists");
    if (res.ok) {
      setPlaylists(await res.json());
    }
  };

  const handleCreateAndAdd = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newPlaylistName.trim()) return;
    setLoading(true);
    
    try {
      const res = await fetch("/api/playlists", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: newPlaylistName, mediaId })
      });
      
      if (res.ok) {
        toast("Playlist créée et vidéo ajoutée !", "success");
        onClose();
        setNewPlaylistName("");
      } else {
        toast("Erreur lors de la création", "error");
      }
    } finally {
      setLoading(false);
    }
  };

  const handleAddToExisting = async (playlistId: string) => {
    setLoading(true);
    try {
      const res = await fetch("/api/playlists/add", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ playlistId, mediaId })
      });
      
      if (res.ok) {
        toast("Ajouté à la playlist", "success");
        onClose();
      } else {
        toast("Erreur", "error");
      }
    } finally {
      setLoading(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/80 backdrop-blur-md p-4">
      <div className="bg-[#12080b] border border-[#e05a68]/30 shadow-[0_0_40px_rgba(224,90,104,0.15)] rounded-2xl w-full max-w-md overflow-hidden relative">
        {/* Header */}
        <div className="flex items-center justify-between p-5 border-b border-[#231400] bg-[#0e0800]">
          <h2 className="text-white font-bold text-lg">Enregistrer dans...</h2>
          <button onClick={onClose} className="p-1.5 text-[#aaaaaa] hover:text-[#e05a68] rounded-full hover:bg-[#e05a68]/10 transition-colors">
            <X size={20} />
          </button>
        </div>

        {/* Playlists List */}
        <div className="max-h-60 overflow-y-auto p-3 custom-scrollbar">
          {playlists.length === 0 ? (
            <p className="text-center text-[#aaaaaa] text-sm py-6">Aucune playlist existante.</p>
          ) : (
            playlists.map(p => (
              <button 
                key={p.id}
                onClick={() => handleAddToExisting(p.id)}
                disabled={loading}
                className="w-full flex items-center justify-between p-3.5 mb-2 rounded-xl hover:bg-[#e05a68]/10 border border-transparent hover:border-[#e05a68]/30 transition-all text-left disabled:opacity-50 group"
              >
                <span className="text-white font-medium group-hover:text-[#e05a68] transition-colors">{p.name}</span>
                <span className="text-xs text-[#aaaaaa] group-hover:text-white transition-colors bg-[#231400] px-2 py-1 rounded-md">{p._count?.media || 0} vidéos</span>
              </button>
            ))
          )}
        </div>

        {/* Create New */}
        <div className="p-5 border-t border-[#231400] bg-[#0e0800]">
          <form onSubmit={handleCreateAndAdd} className="flex gap-3">
            <input 
              type="text"
              placeholder="Nouvelle playlist..."
              value={newPlaylistName}
              onChange={(e) => setNewPlaylistName(e.target.value)}
              className="flex-1 bg-[#12080b] border border-[#2e1217] rounded-xl px-4 py-2.5 text-white text-sm focus:outline-none focus:border-[#e05a68] focus:ring-1 focus:ring-[#e05a68] transition-all"
            />
            <button 
              type="submit" 
              disabled={loading || !newPlaylistName.trim()}
              className="px-5 py-2.5 rounded-xl font-bold text-sm bg-gradient-to-r from-[#e05a68] to-[#f08592] text-black hover:brightness-110 disabled:opacity-50 transition-all flex items-center gap-1 shadow-[0_0_15px_rgba(224,90,104,0.3)]"
            >
              <Plus size={16} /> Créer
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}

