"use client"

import type React from "react"

import { useState, useRef } from "react"
import Image from "next/image"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { ChevronLeft, Camera, Plus, Search, X, Loader2 } from "lucide-react"
import { BottomNav } from "@/components/bottom-nav"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Switch } from "@/components/ui/switch"
import { useAuth } from "@/components/auth-provider"
import { useToast } from "@/hooks/use-toast"
import useSWR from "swr"

interface Track {
  id: string
  title: string
  artist: string
  artist_name?: string
  image?: string
  cover_url?: string
  duration: number
  audio_url?: string
}

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

export default function CreatePlaylistPage() {
  const router = useRouter()
  const { user } = useAuth()
  const { toast } = useToast()
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [name, setName] = useState("")
  const [description, setDescription] = useState("")
  const [isPublic, setIsPublic] = useState(false)
  const [isCollaborative, setIsCollaborative] = useState(false)
  const [selectedTracks, setSelectedTracks] = useState<Track[]>([])
  const [showTrackPicker, setShowTrackPicker] = useState(false)
  const [searchQuery, setSearchQuery] = useState("")
  const [isCreating, setIsCreating] = useState(false)
  const [coverImage, setCoverImage] = useState<string | null>(null)
  const [isUploadingCover, setIsUploadingCover] = useState(false)

  const { data: tracksData, isLoading: tracksLoading } = useSWR(
    showTrackPicker ? `/api/tracks?limit=100&status=published` : null,
    fetcher,
    { dedupingInterval: 60000 },
  )

  const allTracks: Track[] = (tracksData?.data || []).map((t: any) => ({
    id: t.id,
    title: t.title,
    artist: t.artist_name || t.artist || "Unknown",
    image: t.cover_url || "/placeholder.svg",
    duration: t.duration || 0,
    audio_url: t.audio_url,
  }))

  const filteredTracks = allTracks.filter(
    (t) =>
      t.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      t.artist.toLowerCase().includes(searchQuery.toLowerCase()),
  )

  const handleCoverUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return

    // Validate file type
    const allowedTypes = ["image/jpeg", "image/png", "image/webp", "image/gif"]
    if (!allowedTypes.includes(file.type)) {
      toast({
        title: "Format non supporté",
        description: "Veuillez choisir une image JPG, PNG, WebP ou GIF",
        variant: "destructive",
      })
      return
    }

    // Validate file size (max 4.5MB)
    if (file.size > 4.5 * 1024 * 1024) {
      toast({
        title: "Image trop volumineuse",
        description: "L'image ne doit pas dépasser 4.5MB",
        variant: "destructive",
      })
      return
    }

    setIsUploadingCover(true)
    try {
      const formData = new FormData()
      formData.append("file", file)

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

      if (!response.ok) {
        const error = await response.json()
        throw new Error(error.error || "Upload failed")
      }

      const data = await response.json()
      setCoverImage(data.url)
      toast({
        title: "Image ajoutée",
        description: "La couverture de la playlist a été mise à jour",
      })
    } catch (error) {
      console.error("Cover upload error:", error)
      toast({
        title: "Erreur d'upload",
        description: error instanceof Error ? error.message : "Impossible d'uploader l'image",
        variant: "destructive",
      })
    } finally {
      setIsUploadingCover(false)
      // Reset input so same file can be selected again
      if (fileInputRef.current) {
        fileInputRef.current.value = ""
      }
    }
  }

  const handleCreate = async () => {
    if (!name.trim() || !user) return

    setIsCreating(true)
    try {
      console.log("[v0] Creating playlist:", {
        name: name.trim(),
        tracks: selectedTracks.length,
        isPublic,
        userId: user.id,
      })

      const response = await fetch("/api/playlists", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: name.trim(),
          description: description.trim(),
          is_public: isPublic,
          is_collaborative: isCollaborative,
          user_id: user.id,
          cover_url: coverImage,
          track_ids: selectedTracks.map((t) => t.id),
        }),
      })

      if (!response.ok) {
        const error = await response.json()
        console.error("[v0] Create playlist failed:", error)
        toast({
          title: "Erreur",
          description: error.error || "Impossible de créer la playlist",
          variant: "destructive",
        })
        return
      }

      const result = await response.json()
      console.log("[v0] Playlist created successfully:", result)

      toast({
        title: "Playlist créée",
        description: `${name} a été créée avec succès`,
      })

      router.push("/library")
    } catch (error) {
      console.error("[v0] Failed to create playlist:", error)
      toast({
        title: "Erreur",
        description: "Une erreur s'est produite lors de la création",
        variant: "destructive",
      })
    } finally {
      setIsCreating(false)
    }
  }

  const addTrack = (track: Track) => {
    if (!selectedTracks.find((t) => t.id === track.id)) {
      setSelectedTracks([...selectedTracks, track])
    }
  }

  const removeTrack = (trackId: string) => {
    setSelectedTracks(selectedTracks.filter((t) => t.id !== trackId))
  }

  const getCoverDisplay = () => {
    // Priority: uploaded cover > grid of tracks > first track > placeholder
    if (coverImage) {
      return <Image src={coverImage || "/placeholder.svg"} alt="Playlist cover" fill className="object-cover" />
    }
    if (selectedTracks.length >= 4) {
      return (
        <div className="grid grid-cols-2 h-full w-full">
          {selectedTracks.slice(0, 4).map((track) => (
            <div key={track.id} className="relative">
              <Image src={track.image || "/placeholder.svg"} alt={track.title} fill className="object-cover" />
            </div>
          ))}
        </div>
      )
    }
    if (selectedTracks.length > 0) {
      return (
        <Image src={selectedTracks[0].image || "/placeholder.svg"} alt="Playlist cover" fill className="object-cover" />
      )
    }
    return <Camera className="h-12 w-12 text-muted-foreground" />
  }

  return (
    <div className="min-h-screen bg-background pb-24">
      <div className="mx-auto max-w-md px-4 py-6">
        {/* Header */}
        <div className="mb-8 flex items-center justify-between">
          <Link href="/library" className="text-foreground hover:text-primary">
            <ChevronLeft className="h-6 w-6" />
          </Link>
          <h1 className="text-lg font-semibold text-foreground">Créer une playlist</h1>
          <button
            onClick={handleCreate}
            className="text-primary font-medium disabled:opacity-50"
            disabled={!name.trim() || isCreating}
          >
            {isCreating ? <Loader2 className="h-4 w-4 animate-spin" /> : "Créer"}
          </button>
        </div>

        {/* Cover Image */}
        <div className="mb-8 flex justify-center">
          <div className="relative">
            <input
              ref={fileInputRef}
              type="file"
              accept="image/jpeg,image/png,image/webp,image/gif"
              onChange={handleCoverUpload}
              className="hidden"
            />
            <button
              onClick={() => fileInputRef.current?.click()}
              disabled={isUploadingCover}
              className="flex h-48 w-48 items-center justify-center rounded-xl bg-secondary overflow-hidden relative hover:opacity-90 transition-opacity"
            >
              {isUploadingCover ? <Loader2 className="h-8 w-8 animate-spin text-primary" /> : getCoverDisplay()}
            </button>
            <button
              onClick={() => fileInputRef.current?.click()}
              disabled={isUploadingCover}
              className="absolute -bottom-2 -right-2 rounded-full bg-primary p-2 text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50"
            >
              {isUploadingCover ? <Loader2 className="h-4 w-4 animate-spin" /> : <Camera className="h-4 w-4" />}
            </button>
          </div>
        </div>

        {/* Form */}
        <div className="space-y-6">
          <div>
            <label className="mb-2 block text-sm font-medium text-foreground">Nom de la playlist</label>
            <Input
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Ma super playlist"
              className="bg-secondary border-0"
            />
          </div>

          <div>
            <label className="mb-2 block text-sm font-medium text-foreground">Description (optionnel)</label>
            <Input
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Ajouter une description..."
              className="bg-secondary border-0"
            />
          </div>

          {/* Options */}
          <div className="space-y-4">
            <div className="flex items-center justify-between rounded-lg bg-secondary p-4">
              <span className="text-foreground">Playlist collaborative</span>
              <Switch checked={isCollaborative} onCheckedChange={setIsCollaborative} />
            </div>
            <div className="flex items-center justify-between rounded-lg bg-secondary p-4">
              <span className="text-foreground">Playlist publique</span>
              <Switch checked={isPublic} onCheckedChange={setIsPublic} />
            </div>
          </div>

          {/* Selected Tracks */}
          <div>
            <div className="flex items-center justify-between mb-2">
              <label className="text-sm font-medium text-foreground">Titres ({selectedTracks.length})</label>
              <button onClick={() => setShowTrackPicker(true)} className="flex items-center gap-1 text-sm text-primary">
                <Plus className="h-4 w-4" />
                Ajouter
              </button>
            </div>
            {selectedTracks.length > 0 ? (
              <div className="space-y-1 max-h-48 overflow-y-auto">
                {selectedTracks.map((track) => (
                  <div key={track.id} className="flex items-center gap-3 rounded-lg bg-secondary p-2">
                    <div className="relative h-10 w-10 overflow-hidden rounded">
                      <Image src={track.image || "/placeholder.svg"} alt={track.title} fill className="object-cover" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="truncate text-sm font-medium text-foreground">{track.title}</p>
                      <p className="truncate text-xs text-muted-foreground">{track.artist}</p>
                    </div>
                    <button
                      onClick={() => removeTrack(track.id)}
                      className="text-muted-foreground hover:text-destructive"
                    >
                      <X className="h-4 w-4" />
                    </button>
                  </div>
                ))}
              </div>
            ) : (
              <button
                onClick={() => setShowTrackPicker(true)}
                className="w-full rounded-lg border-2 border-dashed border-muted p-8 text-center text-muted-foreground hover:border-primary hover:text-primary"
              >
                Ajouter des titres à votre playlist
              </button>
            )}
          </div>
        </div>

        {/* Create Button */}
        <div className="mt-8">
          <Button onClick={handleCreate} className="w-full rounded-full" disabled={!name.trim() || isCreating}>
            {isCreating ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Création...
              </>
            ) : (
              "Créer la playlist"
            )}
          </Button>
        </div>
      </div>

      {/* Track Picker Modal */}
      {showTrackPicker && (
        <div className="fixed inset-0 z-50 bg-background/95 backdrop-blur">
          <div className="mx-auto max-w-md px-4 py-6">
            <div className="flex items-center gap-4 mb-6">
              <button onClick={() => setShowTrackPicker(false)} className="text-foreground">
                <ChevronLeft className="h-6 w-6" />
              </button>
              <div className="flex-1 relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  placeholder="Rechercher des titres..."
                  className="pl-10 bg-secondary border-0"
                />
              </div>
            </div>

            {tracksLoading ? (
              <div className="flex items-center justify-center py-12">
                <Loader2 className="h-8 w-8 animate-spin text-primary" />
              </div>
            ) : filteredTracks.length === 0 ? (
              <div className="text-center py-12 text-muted-foreground">
                {searchQuery ? "Aucun titre trouvé" : "Aucun titre disponible"}
              </div>
            ) : (
              <div className="space-y-1 max-h-[70vh] overflow-y-auto">
                {filteredTracks.map((track) => {
                  const isSelected = selectedTracks.some((t) => t.id === track.id)
                  return (
                    <button
                      key={track.id}
                      onClick={() => (isSelected ? removeTrack(track.id) : addTrack(track))}
                      className={`flex w-full items-center gap-3 rounded-lg p-2 transition-colors text-left ${isSelected ? "bg-primary/20" : "hover:bg-secondary"}`}
                    >
                      <div className="relative h-12 w-12 overflow-hidden rounded">
                        <Image
                          src={track.image || "/placeholder.svg"}
                          alt={track.title}
                          fill
                          className="object-cover"
                        />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="truncate font-medium text-foreground">{track.title}</p>
                        <p className="truncate text-sm text-muted-foreground">{track.artist}</p>
                      </div>
                      {isSelected && <span className="text-primary text-sm">Ajouté</span>}
                    </button>
                  )
                })}
              </div>
            )}

            <div className="fixed bottom-6 left-4 right-4 mx-auto max-w-md">
              <Button onClick={() => setShowTrackPicker(false)} className="w-full rounded-full">
                Terminé ({selectedTracks.length} titres)
              </Button>
            </div>
          </div>
        </div>
      )}

      <BottomNav />
    </div>
  )
}
