"use client"

import type React from "react"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { ChevronLeft, Upload, Trash2, Plus, Search, Loader2, Music } from "lucide-react"
import Link from "next/link"
import Image from "next/image"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { useAuth } from "@/components/auth-provider"
import { toast } from "sonner"
import useSWR from "swr"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog"
import { getImageUrl } from "@/lib/image-utils"

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

export default function EditMixPage({ params }: { params: { id: string } }) {
  const { id } = params
  const router = useRouter()
  const { user } = useAuth()
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [coverPreview, setCoverPreview] = useState<string | null>(null)
  const [coverFile, setCoverFile] = useState<File | null>(null)
  const [searchQuery, setSearchQuery] = useState("")
  const [isAddingTrack, setIsAddingTrack] = useState(false)
  const [showAddDialog, setShowAddDialog] = useState(false)

  const { data: mixData, isLoading, mutate } = useSWR(`/api/playlists/${id}`, fetcher)
  const { data: searchResults, isLoading: searching } = useSWR(
    searchQuery.length >= 2 ? `/api/tracks?search=${encodeURIComponent(searchQuery)}&limit=20` : null,
    fetcher,
  )

  const mix = mixData?.data
  const tracks = mix?.tracks || []
  const availableTracks = searchResults?.data || []

  const [formData, setFormData] = useState({
    name: "",
    description: "",
    isPublic: true,
  })

  // Update form when mix data loads
  useEffect(() => {
    if (mix) {
      setFormData({
        name: mix.name || "",
        description: mix.description || "",
        isPublic: mix.is_public ?? true,
      })
      if (mix.cover_url) {
        setCoverPreview(mix.cover_url)
      }
    }
  }, [mix])

  // Check if user owns this mix
  useEffect(() => {
    if (mix && user && mix.user_id !== user.id) {
      toast.error("Vous n'êtes pas autorisé à modifier ce mix")
      router.push("/home")
    }
  }, [mix, user, router])

  const handleCoverChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      setCoverFile(file)
      const reader = new FileReader()
      reader.onloadend = () => {
        setCoverPreview(reader.result as string)
      }
      reader.readAsDataURL(file)
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!formData.name.trim()) {
      toast.error("Le nom du mix est requis")
      return
    }

    setIsSubmitting(true)

    try {
      let coverUrl = mix?.cover_url

      // Upload new cover image if changed
      if (coverFile) {
        const imageFormData = new FormData()
        imageFormData.append("file", coverFile)

        const uploadRes = await fetch("/api/upload/image", {
          method: "POST",
          body: imageFormData,
        })

        if (uploadRes.ok) {
          const uploadData = await uploadRes.json()
          coverUrl = uploadData.url
        }
      }

      // Update the playlist/mix
      const response = await fetch(`/api/playlists/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: formData.name,
          description: formData.description,
          cover_url: coverUrl,
          isPublic: formData.isPublic,
        }),
      })

      if (!response.ok) {
        throw new Error("Failed to update mix")
      }

      toast.success("Mix mis à jour avec succès!")
      mutate()
    } catch (error) {
      console.error("Error updating mix:", error)
      toast.error("Erreur lors de la mise à jour du mix")
    } finally {
      setIsSubmitting(false)
    }
  }

  const handleAddTrack = async (trackId: string) => {
    setIsAddingTrack(true)
    try {
      const response = await fetch(`/api/playlists/${id}/tracks`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ trackId: trackId }),
      })

      if (!response.ok) {
        const error = await response.json()
        throw new Error(error.error || "Failed to add track")
      }

      toast.success("Titre ajouté au mix!")
      mutate()
      setSearchQuery("")
    } catch (error: any) {
      toast.error(error.message || "Erreur lors de l'ajout du titre")
    } finally {
      setIsAddingTrack(false)
    }
  }

  const handleRemoveTrack = async (trackId: string) => {
    try {
      const response = await fetch(`/api/playlists/${id}/tracks/${trackId}`, {
        method: "DELETE",
      })

      if (!response.ok) {
        throw new Error("Failed to remove track")
      }

      toast.success("Titre retiré du mix")
      mutate()
    } catch (error) {
      toast.error("Erreur lors de la suppression du titre")
    }
  }

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

  if (!mix) {
    return (
      <div className="flex min-h-screen flex-col items-center justify-center bg-background">
        <p className="text-muted-foreground">Mix non trouvé</p>
        <Link href="/home" className="mt-4 text-primary hover:underline">
          Retour à l'accueil
        </Link>
      </div>
    )
  }

  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-6 flex items-center gap-4">
          <Link href="/home" className="text-foreground hover:text-primary">
            <ChevronLeft className="h-6 w-6" />
          </Link>
          <h1 className="text-xl font-bold text-foreground">Modifier le Mix</h1>
        </div>

        <form onSubmit={handleSubmit} className="space-y-6">
          {/* Cover Image */}
          <div className="flex flex-col items-center">
            <label
              htmlFor="cover"
              className="relative flex h-40 w-40 cursor-pointer items-center justify-center overflow-hidden rounded-xl border-2 border-dashed border-muted-foreground/25 bg-secondary/50 transition-colors hover:border-primary/50"
            >
              {coverPreview ? (
                <Image
                  src={
                    getImageUrl(coverPreview, "playlist") ||
                    "/placeholder.svg?height=160&width=160&query=music playlist" ||
                    "/placeholder.svg" ||
                    "/placeholder.svg"
                  }
                  alt="Cover preview"
                  fill
                  className="object-cover"
                />
              ) : (
                <div className="flex flex-col items-center gap-2 text-muted-foreground">
                  <Upload className="h-8 w-8" />
                  <span className="text-xs">Modifier l'image</span>
                </div>
              )}
            </label>
            <input id="cover" type="file" accept="image/*" onChange={handleCoverChange} className="hidden" />
          </div>

          {/* Name */}
          <div className="space-y-2">
            <Label htmlFor="name">Nom du mix</Label>
            <Input
              id="name"
              placeholder="Mon super mix"
              value={formData.name}
              onChange={(e) => setFormData({ ...formData, name: e.target.value })}
              required
            />
          </div>

          {/* Description */}
          <div className="space-y-2">
            <Label htmlFor="description">Description (optionnel)</Label>
            <Textarea
              id="description"
              placeholder="Décrivez votre mix..."
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              rows={3}
            />
          </div>

          {/* Public toggle */}
          <div className="flex items-center justify-between rounded-lg bg-secondary/50 p-4">
            <div className="space-y-0.5">
              <Label htmlFor="public">Mix public</Label>
              <p className="text-xs text-muted-foreground">Les autres utilisateurs pourront voir ce mix</p>
            </div>
            <Switch
              id="public"
              checked={formData.isPublic}
              onCheckedChange={(checked) => setFormData({ ...formData, isPublic: checked })}
            />
          </div>

          {/* Save button */}
          <Button type="submit" className="w-full" disabled={isSubmitting}>
            {isSubmitting ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Enregistrement...
              </>
            ) : (
              "Enregistrer les modifications"
            )}
          </Button>
        </form>

        {/* Tracks Section */}
        <div className="mt-8">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold text-foreground">Titres ({tracks.length})</h2>
            <Dialog open={showAddDialog} onOpenChange={setShowAddDialog}>
              <DialogTrigger asChild>
                <Button size="sm" variant="outline">
                  <Plus className="mr-2 h-4 w-4" />
                  Ajouter
                </Button>
              </DialogTrigger>
              <DialogContent className="max-h-[80vh] overflow-hidden flex flex-col">
                <DialogHeader>
                  <DialogTitle>Ajouter des titres</DialogTitle>
                </DialogHeader>

                {/* Search */}
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                  <Input
                    placeholder="Rechercher un titre..."
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    className="pl-10"
                  />
                </div>

                {/* Results */}
                <div className="flex-1 overflow-y-auto mt-4 space-y-2 max-h-[50vh]">
                  {searching ? (
                    <div className="flex items-center justify-center py-8">
                      <Loader2 className="h-6 w-6 animate-spin text-primary" />
                    </div>
                  ) : searchQuery.length < 2 ? (
                    <p className="text-center text-muted-foreground text-sm py-8">
                      Tapez au moins 2 caractères pour rechercher
                    </p>
                  ) : availableTracks.length === 0 ? (
                    <p className="text-center text-muted-foreground text-sm py-8">Aucun résultat trouvé</p>
                  ) : (
                    availableTracks.map((track: any) => {
                      const isInMix = tracks.some((t: any) => t.id === track.id)
                      return (
                        <div key={track.id} className="flex items-center gap-3 rounded-lg bg-secondary/50 p-3">
                          <div className="relative h-10 w-10 overflow-hidden rounded">
                            <Image
                              src={
                                getImageUrl(track.cover_url || track.album_cover, "track") ||
                                "/placeholder.svg?height=40&width=40&query=music"
                              }
                              alt={track.title}
                              fill
                              className="object-cover"
                            />
                          </div>
                          <div className="flex-1 min-w-0">
                            <p className="text-sm font-medium text-foreground truncate">{track.title}</p>
                            <p className="text-xs text-muted-foreground truncate">{track.artist_name}</p>
                          </div>
                          <Button
                            size="sm"
                            variant={isInMix ? "secondary" : "default"}
                            disabled={isInMix || isAddingTrack}
                            onClick={() => handleAddTrack(track.id)}
                          >
                            {isInMix ? "Ajouté" : "Ajouter"}
                          </Button>
                        </div>
                      )
                    })
                  )}
                </div>
              </DialogContent>
            </Dialog>
          </div>

          {/* Track list */}
          {tracks.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-12 text-center rounded-xl bg-secondary/30">
              <Music className="h-12 w-12 text-muted-foreground mb-3" />
              <p className="text-muted-foreground text-sm">Aucun titre dans ce mix</p>
              <Button variant="link" className="mt-2" onClick={() => setShowAddDialog(true)}>
                Ajouter des titres
              </Button>
            </div>
          ) : (
            <div className="space-y-2">
              {tracks.map((track: any, index: number) => (
                <div key={track.id} className="flex items-center gap-3 rounded-lg bg-secondary/50 p-3">
                  <span className="text-xs text-muted-foreground w-5">{index + 1}</span>
                  <div className="relative h-10 w-10 overflow-hidden rounded">
                    <Image
                      src={
                        getImageUrl(track.cover_url || track.album_cover, "track") ||
                        "/placeholder.svg?height=40&width=40&query=music"
                      }
                      alt={track.title}
                      fill
                      className="object-cover"
                    />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-foreground truncate">{track.title}</p>
                    <p className="text-xs text-muted-foreground truncate">{track.artist_name}</p>
                  </div>
                  <button
                    onClick={() => handleRemoveTrack(track.id)}
                    className="text-muted-foreground hover:text-destructive transition-colors"
                  >
                    <Trash2 className="h-4 w-4" />
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
