"use client"

import type React from "react"
import { useState, useRef } from "react"
import { useRouter } from "next/navigation"
import { Upload, Music, ImageIcon, X, Plus, Loader2, CheckCircle } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { useAuth } from "@/components/auth-provider"
import { useToast } from "@/hooks/use-toast"
import { validateAudioFile } from "@/lib/audio-utils"
import { validateImageFile } from "@/lib/image-utils"
import { uploadAudioFile } from "@/lib/audio-utils"
import useSWR from "swr"

interface Genre {
  id: string
  name: string
  slug: string
}

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

export default function ArtistUploadPage() {
  const router = useRouter()
  const { user } = useAuth()
  const { toast } = useToast()
  const audioInputRef = useRef<HTMLInputElement>(null)
  const coverInputRef = useRef<HTMLInputElement>(null)

  const { data: genresData, isLoading: genresLoading } = useSWR<{ data: Genre[] }>("/api/genres?limit=100", fetcher)
  const genres = genresData?.data || []

  const [audioFile, setAudioFile] = useState<File | null>(null)
  const [coverFile, setCoverFile] = useState<File | null>(null)
  const [coverPreview, setCoverPreview] = useState<string | null>(null)
  const [audioDuration, setAudioDuration] = useState<number>(0)
  const [isUploading, setIsUploading] = useState(false)
  const [uploadProgress, setUploadProgress] = useState(0)
  const [uploadSuccess, setUploadSuccess] = useState(false)
  const [formData, setFormData] = useState({
    title: "",
    album: "",
    genre: "",
    releaseDate: "",
    description: "",
    lyrics: "",
    explicit: false,
  })

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

    const validation = validateAudioFile(file)
    if (!validation.valid) {
      toast({
        title: "Fichier invalide",
        description: validation.error,
        variant: "destructive",
      })
      return
    }

    setAudioFile(file)

    // Extract duration
    const audio = new Audio()
    const url = URL.createObjectURL(file)
    audio.src = url
    audio.addEventListener("loadedmetadata", () => {
      const durationMs = Math.floor(audio.duration * 1000)
      setAudioDuration(durationMs)
      URL.revokeObjectURL(url)
    })
    audio.addEventListener("error", () => {
      toast({
        title: "Erreur",
        description: "Impossible de lire le fichier audio",
        variant: "destructive",
      })
      URL.revokeObjectURL(url)
    })
  }

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

    const validation = validateImageFile(file)
    if (!validation.valid) {
      toast({
        title: "Image invalide",
        description: validation.error,
        variant: "destructive",
      })
      return
    }

    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 (!user) {
      toast({
        title: "Erreur",
        description: "Vous devez être connecté",
        variant: "destructive",
      })
      return
    }

    if (!user.artistId) {
      toast({
        title: "Erreur",
        description: "Votre profil artiste n'est pas configuré. Veuillez vous reconnecter.",
        variant: "destructive",
      })
      return
    }

    if (!audioFile) {
      toast({
        title: "Erreur",
        description: "Veuillez sélectionner un fichier audio",
        variant: "destructive",
      })
      return
    }

    setIsUploading(true)
    setUploadProgress(0)

    try {
      console.log("[v0] Uploading audio file via chunked upload:", audioFile.name, audioFile.size, "bytes")

      const { url: audioUrl, duration: durationSeconds } = await uploadAudioFile(audioFile, (progress) => {
        setUploadProgress(Math.floor(progress * 0.7))
      })

      const durationMs = durationSeconds * 1000
      console.log("[v0] Audio uploaded successfully:", audioUrl, "duration:", durationMs, "ms")
      setUploadProgress(75)

      // Upload cover if provided
      let coverUrl = ""
      if (coverFile) {
        console.log("[v0] Uploading cover file")
        const formData = new FormData()
        formData.append("file", coverFile)
        formData.append("type", "cover")

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

        if (!coverResponse.ok) {
          throw new Error("Failed to upload cover image")
        }

        const coverData = await coverResponse.json()
        coverUrl = coverData.url
        setUploadProgress(85)
      }

      const trackPayload = {
        title: formData.title,
        artist_id: user.artistId,
        album_id: null,
        duration_ms: durationMs,
        audio_url: audioUrl,
        cover_url: coverUrl || null,
        genre_id: formData.genre || null,
        is_explicit: formData.explicit,
        lyrics: formData.lyrics || null,
        status: "pending",
      }

      console.log("[v0] Creating track in database")
      const trackResponse = await fetch("/api/tracks", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(trackPayload),
      })

      const responseData = await trackResponse.json()

      if (!trackResponse.ok) {
        throw new Error(responseData.error || "Erreur lors de la création du titre")
      }

      setUploadProgress(100)
      setUploadSuccess(true)
      toast({
        title: "Upload réussi",
        description: "Votre titre est en attente de validation par l'administrateur",
      })

      setTimeout(() => {
        router.push("/artist/tracks")
      }, 1500)
    } catch (error) {
      console.error("[v0] Upload error:", error)
      toast({
        title: "Erreur",
        description: error instanceof Error ? error.message : "Erreur lors de l'upload",
        variant: "destructive",
      })
      setIsUploading(false)
      setUploadProgress(0)
    }
  }

  if (uploadSuccess) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="text-center">
          <div className="w-20 h-20 bg-green-500/20 rounded-full flex items-center justify-center mx-auto mb-4">
            <CheckCircle className="w-10 h-10 text-green-400" />
          </div>
          <h2 className="text-2xl font-bold text-white mb-2">Upload réussi</h2>
          <p className="text-zinc-400">Votre titre est en attente de validation</p>
        </div>
      </div>
    )
  }

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-white">Uploader un titre</h1>
        <p className="text-zinc-400">Partagez votre musique avec le monde</p>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        <div className="grid lg:grid-cols-2 gap-6">
          <Card className="bg-zinc-800/50 border-zinc-700">
            <CardHeader>
              <CardTitle className="text-white flex items-center gap-2">
                <Music className="w-5 h-5 text-purple-400" />
                Fichier audio
              </CardTitle>
            </CardHeader>
            <CardContent>
              <input ref={audioInputRef} type="file" accept="audio/*" onChange={handleAudioSelect} className="hidden" />

              {audioFile ? (
                <div className="flex items-center gap-3 p-4 bg-zinc-900/50 rounded-lg">
                  <div className="w-12 h-12 bg-purple-500/20 rounded-lg flex items-center justify-center">
                    <Music className="w-6 h-6 text-purple-400" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-white font-medium truncate">{audioFile.name}</p>
                    <p className="text-zinc-400 text-sm">{(audioFile.size / 1024 / 1024).toFixed(2)} MB</p>
                    {audioDuration > 0 && (
                      <p className="text-zinc-400 text-sm">
                        Durée: {Math.floor(audioDuration / 60000)}:
                        {Math.floor((audioDuration % 60000) / 1000)
                          .toString()
                          .padStart(2, "0")}
                      </p>
                    )}
                  </div>
                  <button
                    type="button"
                    onClick={() => setAudioFile(null)}
                    disabled={isUploading}
                    className="text-zinc-400 hover:text-white disabled:opacity-50"
                  >
                    <X className="w-5 h-5" />
                  </button>
                </div>
              ) : (
                <button
                  type="button"
                  onClick={() => audioInputRef.current?.click()}
                  disabled={isUploading}
                  className="w-full h-40 border-2 border-dashed border-zinc-700 rounded-xl flex flex-col items-center justify-center gap-2 hover:border-purple-500/50 hover:bg-purple-500/5 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <Upload className="w-8 h-8 text-zinc-500" />
                  <p className="text-zinc-400">Cliquez pour sélectionner un fichier</p>
                  <p className="text-zinc-500 text-sm">MP3, WAV, FLAC, AAC, OGG (max 50MB)</p>
                </button>
              )}
            </CardContent>
          </Card>

          <Card className="bg-zinc-800/50 border-zinc-700">
            <CardHeader>
              <CardTitle className="text-white flex items-center gap-2">
                <ImageIcon className="w-5 h-5 text-purple-400" />
                Pochette
              </CardTitle>
            </CardHeader>
            <CardContent>
              <input ref={coverInputRef} type="file" accept="image/*" onChange={handleCoverSelect} className="hidden" />

              {coverPreview ? (
                <div className="relative">
                  <img
                    src={coverPreview || "/placeholder.svg"}
                    alt="Cover preview"
                    className="w-full aspect-square object-cover rounded-lg"
                  />
                  <button
                    type="button"
                    onClick={() => {
                      setCoverFile(null)
                      setCoverPreview(null)
                    }}
                    disabled={isUploading}
                    className="absolute top-2 right-2 w-8 h-8 bg-black/50 rounded-full flex items-center justify-center text-white hover:bg-black/70 disabled:opacity-50"
                  >
                    <X className="w-4 h-4" />
                  </button>
                </div>
              ) : (
                <button
                  type="button"
                  onClick={() => coverInputRef.current?.click()}
                  disabled={isUploading}
                  className="w-full aspect-square border-2 border-dashed border-zinc-700 rounded-xl flex flex-col items-center justify-center gap-2 hover:border-purple-500/50 hover:bg-purple-500/5 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  <Plus className="w-8 h-8 text-zinc-500" />
                  <p className="text-zinc-400">Ajouter une pochette</p>
                  <p className="text-zinc-500 text-sm">JPG, PNG, WebP (max 5MB)</p>
                </button>
              )}
            </CardContent>
          </Card>
        </div>

        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardHeader>
            <CardTitle className="text-white">Détails du titre</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid sm:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label className="text-zinc-300">Titre *</Label>
                <Input
                  required
                  value={formData.title}
                  onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                  placeholder="Nom du titre"
                  disabled={isUploading}
                  className="bg-zinc-900/50 border-zinc-700 text-white"
                />
              </div>
              <div className="space-y-2">
                <Label className="text-zinc-300">Album</Label>
                <Input
                  value={formData.album}
                  onChange={(e) => setFormData({ ...formData, album: e.target.value })}
                  placeholder="Nom de l'album (optionnel)"
                  disabled={isUploading}
                  className="bg-zinc-900/50 border-zinc-700 text-white"
                />
              </div>
            </div>

            <div className="grid sm:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label className="text-zinc-300">Genre *</Label>
                <Select
                  value={formData.genre}
                  onValueChange={(value) => setFormData({ ...formData, genre: value })}
                  disabled={isUploading || genresLoading}
                >
                  <SelectTrigger className="bg-zinc-900/50 border-zinc-700 text-white">
                    <SelectValue placeholder={genresLoading ? "Chargement..." : "Sélectionner un genre"} />
                  </SelectTrigger>
                  <SelectContent className="bg-zinc-800 border-zinc-700">
                    {genres.length > 0 ? (
                      genres.map((genre) => (
                        <SelectItem key={genre.id} value={genre.id}>
                          {genre.name}
                        </SelectItem>
                      ))
                    ) : (
                      <SelectItem value="none" disabled>
                        Aucun genre disponible
                      </SelectItem>
                    )}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label className="text-zinc-300">Date de sortie</Label>
                <Input
                  type="date"
                  value={formData.releaseDate}
                  onChange={(e) => setFormData({ ...formData, releaseDate: e.target.value })}
                  disabled={isUploading}
                  className="bg-zinc-900/50 border-zinc-700 text-white"
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label className="text-zinc-300">Description</Label>
              <Textarea
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                placeholder="Décrivez votre titre..."
                disabled={isUploading}
                className="bg-zinc-900/50 border-zinc-700 text-white min-h-[100px]"
              />
            </div>

            <div className="space-y-2">
              <Label className="text-zinc-300">Paroles</Label>
              <Textarea
                value={formData.lyrics}
                onChange={(e) => setFormData({ ...formData, lyrics: e.target.value })}
                placeholder="Ajoutez les paroles (optionnel)..."
                disabled={isUploading}
                className="bg-zinc-900/50 border-zinc-700 text-white min-h-[150px]"
              />
            </div>

            <label className="flex items-center gap-2 text-zinc-300">
              <input
                type="checkbox"
                checked={formData.explicit}
                onChange={(e) => setFormData({ ...formData, explicit: e.target.checked })}
                disabled={isUploading}
                className="rounded bg-zinc-700 border-zinc-600"
              />
              Contenu explicite
            </label>
          </CardContent>
        </Card>

        <div className="flex items-center justify-end gap-4">
          <Button
            type="button"
            variant="ghost"
            onClick={() => router.back()}
            disabled={isUploading}
            className="text-zinc-400"
          >
            Annuler
          </Button>
          <Button
            type="submit"
            disabled={!audioFile || !formData.title || !formData.genre || isUploading}
            className="bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {isUploading ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                Upload en cours...
              </>
            ) : (
              <>
                <Upload className="w-4 h-4 mr-2" />
                Publier
              </>
            )}
          </Button>
        </div>
      </form>
    </div>
  )
}
