"use client"

import { useState, useEffect } from "react"
import { X, Plus, Check, Music, Loader2, Lock } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { useUser } from "@/components/user-provider"
import { useAuth } from "@/components/auth-provider"
import Image from "next/image"

interface TrackLike {
  id: string
  title?: string
  artist?: string
  image?: string
  cover_url?: string
  duration?: number
  audioUrl?: string
  audio_url?: string
}

interface AddToPlaylistModalProps {
  track: TrackLike
  isOpen?: boolean
  onClose?: () => void
  open?: boolean
  onOpenChange?: (open: boolean) => void
}

export function AddToPlaylistModal({ track, isOpen, onClose, open, onOpenChange }: AddToPlaylistModalProps) {
  const { playlists, refreshPlaylists, addTrackToPlaylist, updatePlaylist } = useUser()
  const { user } = useAuth()
  const [showCreate, setShowCreate] = useState(false)
  const [newPlaylistName, setNewPlaylistName] = useState("")
  const [addedTo, setAddedTo] = useState<Set<string>>(new Set())
  const [isCreating, setIsCreating] = useState(false)
  const [loadingPlaylistId, setLoadingPlaylistId] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)

  const isVisible = open ?? isOpen ?? false
  const handleClose = () => {
    onClose?.()
    onOpenChange?.(false)
    setShowCreate(false)
    setNewPlaylistName("")
    setError(null)
  }

  useEffect(() => {
    if (isVisible) {
      setAddedTo(new Set())
      setError(null)
    }
  }, [isVisible, track?.id])

  if (!isVisible) return null

  if (!user) {
    return (
      <div
        className="fixed inset-0 z-50 flex items-end justify-center bg-black/60 backdrop-blur-sm"
        onClick={handleClose}
      >
        <div
          className="w-full max-w-md rounded-t-3xl bg-zinc-900 border-t border-zinc-800 p-6 pb-8"
          onClick={(e) => e.stopPropagation()}
        >
          <div className="mb-6 flex items-center justify-between">
            <h2 className="text-lg font-semibold text-white">Ajouter à une playlist</h2>
            <button onClick={handleClose} className="text-zinc-400 hover:text-white">
              <X className="h-6 w-6" />
            </button>
          </div>
          <p className="text-center text-zinc-400 py-8">Connectez-vous pour créer et gérer vos playlists.</p>
        </div>
      </div>
    )
  }

  const trackId = track?.id

  const handleAddToPlaylist = async (playlistId: string) => {
    if (!trackId) {
      setError("Erreur: piste invalide - ID manquant")
      return
    }

    setLoadingPlaylistId(playlistId)
    setError(null)

    try {
      // Make direct API call
      const response = await fetch(`/api/playlists/${playlistId}/tracks`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ trackId }),
      })

      const data = await response.json()

      if (!response.ok) {
        throw new Error(data.error || "Échec de l'ajout")
      }

      // Update local state via user-provider
      addTrackToPlaylist(playlistId, {
        id: trackId,
        title: track.title,
        artist: track.artist,
        image: track.image || track.cover_url,
        duration: track.duration,
        audioUrl: track.audioUrl || track.audio_url,
      }).catch(() => {}) // Ignore errors since we already made the API call

      setAddedTo((prev) => new Set(prev).add(playlistId))

      setTimeout(() => {
        handleClose()
      }, 500)
    } catch (error: any) {
      console.error("Error adding to playlist:", error)
      setError(error.message || "Impossible d'ajouter le titre à la playlist")
    } finally {
      setLoadingPlaylistId(null)
    }
  }

  const handleCreatePlaylist = async () => {
    if (!newPlaylistName.trim() || !user?.id) return
    setIsCreating(true)
    setError(null)

    try {
      // Create playlist via direct API call
      const createResponse = await fetch("/api/playlists", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: newPlaylistName.trim(),
          user_id: user.id,
          is_public: false,
        }),
      })

      const createData = await createResponse.json()

      if (!createResponse.ok) {
        throw new Error(createData.error || "Échec de la création")
      }

      const newPlaylistId = createData.data?.id

      if (newPlaylistId && trackId) {
        // Add track to the new playlist
        const addResponse = await fetch(`/api/playlists/${newPlaylistId}/tracks`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ trackId }),
        })

        if (!addResponse.ok) {
          const addData = await addResponse.json()
          console.error("Failed to add track:", addData)
        }

        setAddedTo((prev) => new Set(prev).add(newPlaylistId))
      }

      await refreshPlaylists()

      setNewPlaylistName("")
      setShowCreate(false)
      setTimeout(() => {
        handleClose()
      }, 500)
    } catch (error: any) {
      console.error("Error creating playlist:", error)
      setError(error.message || "Impossible de créer la playlist")
    } finally {
      setIsCreating(false)
    }
  }

  const trackImage = track?.image || track?.cover_url || "/diverse-group-making-music.png"

  return (
    <div
      className="fixed inset-0 z-50 flex items-end justify-center bg-black/60 backdrop-blur-sm"
      onClick={handleClose}
    >
      <div
        className="w-full max-w-md rounded-t-3xl bg-zinc-900 border-t border-zinc-800 p-6 pb-8"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="mb-6 flex items-center justify-between">
          <h2 className="text-lg font-semibold text-white">Ajouter à une playlist</h2>
          <button onClick={handleClose} className="text-zinc-400 hover:text-white">
            <X className="h-6 w-6" />
          </button>
        </div>

        {error && <div className="mb-4 p-3 rounded-lg bg-red-500/10 text-red-400 text-sm">{error}</div>}

        {/* Track info */}
        <div className="mb-6 flex items-center gap-3 rounded-lg bg-zinc-800/50 p-3">
          <div className="relative h-12 w-12 overflow-hidden rounded">
            <Image src={trackImage || "/placeholder.svg"} alt={track?.title || "Track"} fill className="object-cover" />
          </div>
          <div className="flex-1 min-w-0">
            <p className="truncate font-medium text-white">{track?.title || "Titre inconnu"}</p>
            <p className="truncate text-sm text-zinc-400">{track?.artist || "Artiste inconnu"}</p>
          </div>
        </div>

        {/* Create new playlist */}
        {showCreate ? (
          <div className="mb-4 space-y-2">
            <div className="flex gap-2">
              <Input
                value={newPlaylistName}
                onChange={(e) => setNewPlaylistName(e.target.value)}
                placeholder="Nom de la playlist"
                className="flex-1 bg-zinc-800 border-zinc-700 text-white placeholder:text-zinc-500"
                autoFocus
                disabled={isCreating}
                onKeyDown={(e) => e.key === "Enter" && handleCreatePlaylist()}
              />
              <Button onClick={handleCreatePlaylist} disabled={!newPlaylistName.trim() || isCreating}>
                {isCreating ? <Loader2 className="h-4 w-4 animate-spin" /> : "Créer"}
              </Button>
              <Button
                variant="ghost"
                onClick={() => setShowCreate(false)}
                disabled={isCreating}
                className="text-zinc-400 hover:text-white hover:bg-zinc-800"
              >
                <X className="h-4 w-4" />
              </Button>
            </div>
          </div>
        ) : (
          <button
            onClick={() => setShowCreate(true)}
            className="mb-4 flex w-full items-center gap-3 rounded-lg border border-dashed border-zinc-700 p-3 text-zinc-400 transition-colors hover:border-primary hover:text-primary"
          >
            <Plus className="h-5 w-5" />
            <span>Créer une nouvelle playlist</span>
          </button>
        )}

        {/* Playlists list */}
        <div className="max-h-64 space-y-2 overflow-y-auto">
          {playlists.length === 0 ? (
            <p className="text-center text-zinc-500 py-4 text-sm">Vous n'avez pas encore de playlist. Créez-en une !</p>
          ) : (
            playlists.map((playlist) => {
              const isAlreadyInPlaylist = playlist.tracks?.some((t: any) => t.id === trackId)
              const isAdded = addedTo.has(playlist.id) || isAlreadyInPlaylist
              const isLoading = loadingPlaylistId === playlist.id

              return (
                <button
                  key={playlist.id}
                  onClick={() => !isAdded && !isLoading && handleAddToPlaylist(playlist.id)}
                  disabled={isAdded || isLoading}
                  className={`flex w-full items-center gap-3 rounded-lg p-3 transition-colors ${
                    isAdded ? "bg-primary/10" : "hover:bg-zinc-800"
                  } ${isAdded || isLoading ? "cursor-default" : "cursor-pointer"}`}
                >
                  <div className="relative h-12 w-12 overflow-hidden rounded bg-zinc-800 flex-shrink-0">
                    {playlist.image && playlist.image !== "/music-playlist.png" ? (
                      <Image
                        src={playlist.image || "/placeholder.svg"}
                        alt={playlist.title}
                        fill
                        className="object-cover"
                      />
                    ) : (
                      <div className="flex h-full w-full items-center justify-center">
                        <Music className="h-6 w-6 text-zinc-500" />
                      </div>
                    )}
                  </div>
                  <div className="flex-1 text-left min-w-0">
                    <p className="truncate font-medium text-white">{playlist.title}</p>
                    <p className="text-sm text-zinc-400">
                      {playlist.is_public === false && <Lock className="inline h-3 w-3 mr-1" />}
                      {playlist.tracks?.length || 0} titres
                    </p>
                  </div>
                  {isLoading ? (
                    <Loader2 className="h-5 w-5 animate-spin text-primary flex-shrink-0" />
                  ) : isAdded ? (
                    <Check className="h-5 w-5 text-primary flex-shrink-0" />
                  ) : null}
                </button>
              )
            })
          )}
        </div>
      </div>
    </div>
  )
}
