"use client"

import type React from "react"

import { useState } from "react"
import Image from "next/image"
import Link from "next/link"
import { useParams, useRouter } from "next/navigation"
import {
  ChevronLeft,
  MoreHorizontal,
  Play,
  Pause,
  Shuffle,
  Heart,
  Download,
  Share2,
  Pencil,
  Loader2,
  Trash2,
  X,
  Check,
  Globe,
  Lock,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { BottomNav } from "@/components/bottom-nav"
import { usePlayer } from "@/components/player-provider"
import { useUser } from "@/components/user-provider"
import { useAuth } from "@/components/auth-provider"
import { useToast } from "@/hooks/use-toast"
import useSWR from "swr"

const fetcher = (url: string) => fetch(url).then((res) => res.json())

const formatDuration = (seconds: number) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins}:${secs.toString().padStart(2, "0")}`
}

export default function PlaylistPage() {
  const { id } = useParams<{ id: string }>()
  const router = useRouter()
  const { user } = useAuth()
  const { deletePlaylist, removeTrackFromPlaylist, updatePlaylist } = useUser()
  const { toast } = useToast()

  const [isEditing, setIsEditing] = useState(false)
  const [editedName, setEditedName] = useState("")
  const [editedDescription, setEditedDescription] = useState("")
  const [isSaving, setIsSaving] = useState(false)
  const [showMoreMenu, setShowMoreMenu] = useState(false)
  const [isDownloading, setIsDownloading] = useState(false)
  const [isDeleting, setIsDeleting] = useState(false)

  const {
    data: playlistData,
    isLoading,
    mutate,
  } = useSWR(id ? `/api/playlists/${id}?current_user_id=${user?.id || ""}` : null, fetcher)

  const playlist = playlistData?.data

  const {
    playTrack,
    playAlbum,
    currentTrack,
    isPlaying,
    togglePlay,
    toggleLike,
    isLiked,
    shuffleEnabled,
    toggleShuffle,
  } = usePlayer()

  const handleStartEdit = () => {
    setEditedName(playlist?.name || playlist?.title || "")
    setEditedDescription(playlist?.description || "")
    setIsEditing(true)
  }

  const handleSaveEdit = async () => {
    if (!editedName.trim()) return
    setIsSaving(true)
    try {
      const response = await fetch(`/api/playlists/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: editedName.trim(),
          description: editedDescription.trim(),
        }),
      })
      if (response.ok) {
        await mutate()
        toast({ title: "Playlist modifiée", description: "Les modifications ont été enregistrées." })
        setIsEditing(false)
      }
    } catch (error) {
      toast({ title: "Erreur", description: "Impossible de modifier la playlist.", variant: "destructive" })
    } finally {
      setIsSaving(false)
    }
  }

  const handleTogglePrivacy = async () => {
    try {
      const newIsPublic = !playlist.is_public
      const response = await fetch(`/api/playlists/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ isPublic: newIsPublic }),
      })

      if (response.ok) {
        await mutate()
        updatePlaylist(id, { is_public: newIsPublic })
        toast({
          title: newIsPublic ? "Playlist publique" : "Playlist privée",
          description: newIsPublic ? "Tout le monde peut voir cette playlist" : "Seul vous pouvez voir cette playlist",
        })
      }
    } catch (error) {
      toast({ title: "Erreur", description: "Impossible de modifier la visibilité.", variant: "destructive" })
    }
  }

  const handleDeletePlaylist = async () => {
    if (!confirm("Êtes-vous sûr de vouloir supprimer cette playlist ?")) return
    setIsDeleting(true)
    try {
      await deletePlaylist(id)
      toast({ title: "Playlist supprimée" })
      router.push("/library")
    } catch (error) {
      toast({ title: "Erreur", description: "Impossible de supprimer la playlist.", variant: "destructive" })
      setIsDeleting(false)
    }
  }

  const handleDownloadAll = async () => {
    if (!user) {
      toast({ title: "Connexion requise", description: "Connectez-vous pour télécharger.", variant: "destructive" })
      return
    }
    setIsDownloading(true)
    try {
      const tracks = playlist?.tracks || []
      for (const track of tracks) {
        await fetch(`/api/tracks/${track.id}/download`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ userId: user.id }),
        })
      }
      toast({ title: "Téléchargement", description: `${tracks.length} titres ajoutés aux téléchargements.` })
    } catch (error) {
      toast({ title: "Erreur", description: "Impossible de télécharger.", variant: "destructive" })
    } finally {
      setIsDownloading(false)
    }
  }

  const handleShare = async () => {
    if (!playlist.is_public) {
      toast({
        title: "Playlist privée",
        description: "Rendez la playlist publique pour la partager.",
        variant: "destructive",
      })
      return
    }

    const url = `${window.location.origin}/playlist/${id}`
    if (navigator.share) {
      try {
        await navigator.share({
          title: playlist?.name || playlist?.title || "Playlist",
          text: `Écoute cette playlist: ${playlist?.name || playlist?.title}`,
          url,
        })
      } catch (error) {
        // User cancelled
      }
    } else {
      await navigator.clipboard.writeText(url)
      toast({ title: "Lien copié", description: "Le lien a été copié dans le presse-papiers." })
    }
  }

  const handleRemoveTrack = async (trackId: string, e: React.MouseEvent) => {
    e.stopPropagation()
    try {
      await removeTrackFromPlaylist(id, trackId)
      await mutate()
      toast({ title: "Titre retiré de la playlist" })
    } catch (error) {
      toast({ title: "Erreur", description: "Impossible de retirer le titre.", variant: "destructive" })
    }
  }

  if (isLoading) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <Loader2 className="w-8 h-8 animate-spin text-primary" />
      </div>
    )
  }

  if (playlistData?.error) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="text-center">
          <Lock className="w-12 h-12 mx-auto mb-4 text-muted-foreground" />
          <p className="text-muted-foreground mb-4">
            {playlistData.error.includes("permission") ? "Cette playlist est privée" : "Playlist non trouvée"}
          </p>
          <Link href="/library">
            <Button>Retour à la bibliothèque</Button>
          </Link>
        </div>
      </div>
    )
  }

  if (!playlist) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="text-center">
          <p className="text-muted-foreground mb-4">Playlist non trouvée</p>
          <Link href="/library">
            <Button>Retour à la bibliothèque</Button>
          </Link>
        </div>
      </div>
    )
  }

  const tracks = playlist.tracks || []
  const totalDuration = tracks.reduce((acc: number, t: any) => acc + (t.duration_ms || 0) / 1000, 0)
  const isPlaylistPlaying = tracks.some((t: any) => t.id === currentTrack?.id) && isPlaying
  const isOwner = user?.id === playlist.user_id
  const canDelete = !!user

  const handlePlayPlaylist = () => {
    if (isPlaylistPlaying) {
      togglePlay()
    } else {
      playAlbum(
        tracks.map((t: any) => ({
          id: t.id,
          title: t.title,
          artist: t.artist_name || "Unknown",
          image: t.cover_url || playlist.cover_url || "/diverse-group-making-music.png",
          duration: Math.floor((t.duration_ms || 0) / 1000),
          audioUrl: t.audio_url,
          cover_url: t.cover_url,
          album_cover: playlist.cover_url,
        })),
        0,
      )
    }
  }

  const handleShufflePlay = () => {
    if (!shuffleEnabled) toggleShuffle()
    playAlbum(
      tracks.map((t: any) => ({
        id: t.id,
        title: t.title,
        artist: t.artist_name || "Unknown",
        image: t.cover_url || playlist.cover_url || "/diverse-group-making-music.png",
        duration: Math.floor((t.duration_ms || 0) / 1000),
        audioUrl: t.audio_url,
        cover_url: t.cover_url,
        album_cover: playlist.cover_url,
      })),
      0,
    )
  }

  return (
    <div className="min-h-screen bg-background pb-24">
      {/* Hero Section */}
      <div className="relative">
        <div className="absolute inset-0 h-72">
          <Image
            src={playlist.cover_url || "/placeholder.svg?height=400&width=400&query=playlist"}
            alt="Playlist Art"
            fill
            className="object-cover opacity-30 blur-xl"
          />
          <div className="absolute inset-0 bg-gradient-to-b from-transparent to-background" />
        </div>

        {/* Header */}
        <div className="relative z-30 flex items-center justify-between p-4">
          <Link href="/library" className="text-foreground hover:text-primary">
            <ChevronLeft className="h-6 w-6" />
          </Link>
          <div className="flex items-center gap-2">
            {isOwner && (
              <button onClick={handleStartEdit} className="text-foreground hover:text-primary">
                <Pencil className="h-5 w-5" />
              </button>
            )}
            <div className="relative">
              <button
                onClick={() => setShowMoreMenu(!showMoreMenu)}
                className={`p-1.5 rounded-md transition-colors ${showMoreMenu ? "bg-primary text-white" : "text-foreground hover:text-primary"}`}
              >
                <MoreHorizontal className="h-6 w-6" />
              </button>
              {showMoreMenu && (
                <>
                  <div className="fixed inset-0 z-40" onClick={() => setShowMoreMenu(false)} />
                  <div className="absolute right-0 mt-2 z-50 w-52 rounded-xl bg-zinc-900 border border-zinc-800 shadow-xl py-2 overflow-hidden">
                    {isOwner && (
                      <>
                        <button
                          onClick={() => {
                            handleTogglePrivacy()
                            setShowMoreMenu(false)
                          }}
                          className="flex w-full items-center gap-3 px-4 py-3 text-sm text-white hover:bg-zinc-800 transition-colors"
                        >
                          {playlist.is_public ? (
                            <>
                              <Lock className="h-5 w-5 text-zinc-400" />
                              Rendre privée
                            </>
                          ) : (
                            <>
                              <Globe className="h-5 w-5 text-zinc-400" />
                              Rendre publique
                            </>
                          )}
                        </button>
                        <div className="my-1 border-t border-zinc-800" />
                      </>
                    )}
                    <button
                      onClick={() => {
                        handleShare()
                        setShowMoreMenu(false)
                      }}
                      className="flex w-full items-center gap-3 px-4 py-3 text-sm text-white hover:bg-zinc-800 transition-colors"
                    >
                      <Share2 className="h-5 w-5 text-zinc-400" />
                      Partager
                    </button>
                    <button
                      onClick={() => {
                        handleDownloadAll()
                        setShowMoreMenu(false)
                      }}
                      className="flex w-full items-center gap-3 px-4 py-3 text-sm text-white hover:bg-zinc-800 transition-colors"
                    >
                      <Download className="h-5 w-5 text-zinc-400" />
                      Tout télécharger
                    </button>
                    {canDelete && (
                      <>
                        <div className="my-1 border-t border-zinc-800" />
                        <button
                          onClick={() => {
                            handleDeletePlaylist()
                            setShowMoreMenu(false)
                          }}
                          className="flex w-full items-center gap-3 px-4 py-3 text-sm text-red-400 hover:bg-zinc-800 transition-colors"
                        >
                          <Trash2 className="h-5 w-5" />
                          Supprimer la playlist
                        </button>
                      </>
                    )}
                  </div>
                </>
              )}
            </div>
          </div>
        </div>

        {/* Playlist Info */}
        <div className="relative z-10 flex flex-col items-center px-4 pb-6 pt-4">
          <div className="relative mb-4 h-40 w-40 overflow-hidden rounded-xl shadow-2xl">
            <Image
              src={playlist.cover_url || "/placeholder.svg?height=300&width=300&query=playlist"}
              alt={playlist.name || playlist.title}
              fill
              className="object-cover"
            />
          </div>
          {isEditing ? (
            <div className="w-full max-w-xs space-y-2">
              <Input
                value={editedName}
                onChange={(e) => setEditedName(e.target.value)}
                placeholder="Nom de la playlist"
                className="text-center"
                autoFocus
              />
              <Input
                value={editedDescription}
                onChange={(e) => setEditedDescription(e.target.value)}
                placeholder="Description (optionnel)"
                className="text-center"
              />
              <div className="flex justify-center gap-2">
                <Button size="sm" onClick={handleSaveEdit} disabled={isSaving || !editedName.trim()}>
                  {isSaving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Check className="h-4 w-4" />}
                </Button>
                <Button size="sm" variant="ghost" onClick={() => setIsEditing(false)} disabled={isSaving}>
                  <X className="h-4 w-4" />
                </Button>
              </div>
            </div>
          ) : (
            <>
              <h1 className="mb-1 text-xl font-bold text-foreground">{playlist.name || playlist.title}</h1>
              <div className="flex items-center gap-2 mb-1">
                {playlist.is_public ? (
                  <span className="flex items-center gap-1 text-xs text-muted-foreground">
                    <Globe className="h-3 w-3" /> Public
                  </span>
                ) : (
                  <span className="flex items-center gap-1 text-xs text-muted-foreground">
                    <Lock className="h-3 w-3" /> Privé
                  </span>
                )}
              </div>
              <p className="mb-1 text-sm text-muted-foreground">{playlist.description || "Ma playlist"}</p>
              <p className="text-sm text-muted-foreground">
                {tracks.length} titres • {Math.floor(totalDuration / 60)} min
              </p>
            </>
          )}
        </div>
      </div>

      <div className="mx-auto max-w-md px-4">
        {/* Action Buttons */}
        <div className="mb-6 flex items-center justify-between">
          <div className="flex items-center gap-4">
            <button className="text-primary">
              <Heart className="h-6 w-6 fill-current" />
            </button>
            <button
              onClick={handleDownloadAll}
              disabled={isDownloading}
              className="text-muted-foreground hover:text-primary disabled:opacity-50"
            >
              {isDownloading ? <Loader2 className="h-6 w-6 animate-spin" /> : <Download className="h-6 w-6" />}
            </button>
            <button onClick={handleShare} className="text-muted-foreground hover:text-primary">
              <Share2 className="h-6 w-6" />
            </button>
          </div>
          <div className="flex items-center gap-3">
            <button
              onClick={handleShufflePlay}
              className={`transition-colors ${shuffleEnabled ? "text-primary" : "text-muted-foreground hover:text-foreground"}`}
            >
              <Shuffle className="h-6 w-6" />
            </button>
            <Button size="icon" className="h-12 w-12 rounded-full" onClick={handlePlayPlaylist}>
              {isPlaylistPlaying ? <Pause className="h-6 w-6" /> : <Play className="h-6 w-6 ml-0.5" />}
            </Button>
          </div>
        </div>

        {/* Track List */}
        <div className="space-y-1">
          {tracks.length === 0 ? (
            <div className="text-center py-12 text-muted-foreground">
              <p>Aucun titre dans cette playlist</p>
            </div>
          ) : (
            tracks.map((track: any) => {
              const isCurrentTrack = currentTrack?.id === track.id
              const trackIsPlaying = isCurrentTrack && isPlaying

              return (
                <div
                  key={track.id}
                  className={`flex w-full items-center gap-3 rounded-lg p-2 transition-colors hover:bg-secondary group ${isCurrentTrack ? "bg-secondary/50" : ""}`}
                >
                  <button
                    onClick={() =>
                      isCurrentTrack
                        ? togglePlay()
                        : playTrack({
                            id: track.id,
                            title: track.title,
                            artist: track.artist_name || "Unknown",
                            image: track.cover_url || playlist.cover_url || "/running-track.png",
                            duration: Math.floor((track.duration_ms || 0) / 1000),
                            audioUrl: track.audio_url,
                            cover_url: track.cover_url,
                            album_cover: playlist.cover_url,
                          })
                    }
                    className="relative h-12 w-12 flex-shrink-0 overflow-hidden rounded-lg"
                  >
                    <Image
                      src={track.cover_url || playlist.cover_url || "/placeholder.svg?height=60&width=60&query=track"}
                      alt={track.title}
                      fill
                      className="object-cover"
                    />
                    {trackIsPlaying && (
                      <div className="absolute inset-0 flex items-center justify-center bg-black/50">
                        <div className="flex gap-0.5">
                          <span className="h-3 w-0.5 animate-pulse bg-white" />
                          <span className="h-4 w-0.5 animate-pulse bg-white" style={{ animationDelay: "150ms" }} />
                          <span className="h-2 w-0.5 animate-pulse bg-white" style={{ animationDelay: "300ms" }} />
                        </div>
                      </div>
                    )}
                  </button>
                  <div className="flex-1 min-w-0">
                    <p className={`truncate font-medium ${isCurrentTrack ? "text-primary" : "text-foreground"}`}>
                      {track.title}
                    </p>
                    <p className="truncate text-sm text-muted-foreground">{track.artist_name}</p>
                  </div>
                  <button
                    onClick={(e) => {
                      e.stopPropagation()
                      toggleLike(track.id)
                    }}
                    className={`p-1 ${isLiked(track.id) ? "text-primary" : "text-muted-foreground"}`}
                  >
                    <Heart className={`h-4 w-4 ${isLiked(track.id) ? "fill-current" : ""}`} />
                  </button>
                  {isOwner && (
                    <button
                      onClick={(e) => handleRemoveTrack(track.id, e)}
                      className="p-1 text-muted-foreground hover:text-destructive opacity-0 group-hover:opacity-100 transition-opacity"
                    >
                      <X className="h-4 w-4" />
                    </button>
                  )}
                  <span className="text-sm text-muted-foreground">
                    {formatDuration(Math.floor((track.duration_ms || 0) / 1000))}
                  </span>
                </div>
              )
            })
          )}
        </div>
      </div>

      <BottomNav />
    </div>
  )
}
