"use client"

import type React from "react"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { ChevronLeft, Upload, Music, Loader2 } 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"

export default function CreateMixPage() {
  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 [formData, setFormData] = useState({
    name: "",
    description: "",
    isPublic: true,
  })

  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 (!user?.id) {
      toast.error("Vous devez être connecté")
      return
    }

    if (!formData.name.trim()) {
      toast.error("Le nom du mix est requis")
      return
    }

    setIsSubmitting(true)

    try {
      let coverUrl = null

      // Upload cover image if provided
      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
        }
      }

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

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

      const data = await response.json()
      toast.success("Mix créé avec succès!")
      router.push(`/mix/${data.data.id}/edit`)
    } catch (error) {
      console.error("Error creating mix:", error)
      toast.error("Erreur lors de la création du mix")
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <div className="min-h-screen bg-background">
      <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">Créer un 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={coverPreview || "/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">Ajouter une 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>

          {/* Submit */}
          <Button type="submit" className="w-full" disabled={isSubmitting}>
            {isSubmitting ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Création...
              </>
            ) : (
              <>
                <Music className="mr-2 h-4 w-4" />
                Créer le mix
              </>
            )}
          </Button>
        </form>
      </div>
    </div>
  )
}
