"use client"

import type React from "react"

import { useState } from "react"
import {
  Plus,
  Calendar,
  Clock,
  CheckCircle,
  AlertCircle,
  MoreHorizontal,
  Edit,
  Trash2,
  Eye,
  Loader2,
  Upload,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Textarea } from "@/components/ui/textarea"
import { useAuth } from "@/components/auth-provider"
import { useToast } from "@/hooks/use-toast"
import useSWR, { mutate } from "swr"
import { upload } from "@vercel/blob/client"

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

export default function ArtistReleasesPage() {
  const { user } = useAuth()
  const { toast } = useToast()
  const artistId = user?.artistId

  const [showNewRelease, setShowNewRelease] = useState(false)
  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
  const [selectedRelease, setSelectedRelease] = useState<any>(null)
  const [uploading, setUploading] = useState(false)
  const [newRelease, setNewRelease] = useState({
    title: "",
    releaseType: "single",
    releaseDate: "",
    coverUrl: "",
    description: "",
  })

  const { data, isLoading } = useSWR(artistId ? `/api/artist/releases?artistId=${artistId}` : null, fetcher)

  const releases = data?.releases || []
  const upcomingReleases = releases.filter((r: any) => r.status === "scheduled")
  const pastReleases = releases.filter((r: any) => r.status === "released")

  const getStatusBadge = (status: string) => {
    switch (status) {
      case "scheduled":
        return (
          <Badge className="bg-blue-500/20 text-blue-400 border-0">
            <Clock className="w-3 h-3 mr-1" /> Planifie
          </Badge>
        )
      case "released":
        return (
          <Badge className="bg-green-500/20 text-green-400 border-0">
            <CheckCircle className="w-3 h-3 mr-1" /> Sorti
          </Badge>
        )
      case "draft":
        return (
          <Badge className="bg-zinc-500/20 text-zinc-400 border-0">
            <AlertCircle className="w-3 h-3 mr-1" /> Brouillon
          </Badge>
        )
      case "cancelled":
        return <Badge className="bg-red-500/20 text-red-400 border-0">Annule</Badge>
      default:
        return <Badge>{status}</Badge>
    }
  }

  const getTypeBadge = (type: string) => {
    switch (type) {
      case "album":
        return <Badge className="bg-purple-500/20 text-purple-400 border-0">Album</Badge>
      case "single":
        return <Badge className="bg-pink-500/20 text-pink-400 border-0">Single</Badge>
      case "ep":
        return <Badge className="bg-orange-500/20 text-orange-400 border-0">EP</Badge>
      default:
        return <Badge>{type}</Badge>
    }
  }

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

    setUploading(true)
    try {
      const blob = await upload(file.name, file, {
        access: "public",
        handleUploadUrl: "/api/upload",
      })
      setNewRelease({ ...newRelease, coverUrl: blob.url })
      toast({ title: "Image telechargee" })
    } catch (error) {
      toast({ title: "Erreur lors du telechargement", variant: "destructive" })
    } finally {
      setUploading(false)
    }
  }

  const handleCreateRelease = async () => {
    try {
      const response = await fetch("/api/artist/releases", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          artistId,
          title: newRelease.title,
          releaseType: newRelease.releaseType,
          releaseDate: newRelease.releaseDate,
          coverUrl: newRelease.coverUrl,
          description: newRelease.description,
        }),
      })

      if (response.ok) {
        toast({ title: "Sortie planifiee avec succes" })
        setShowNewRelease(false)
        setNewRelease({ title: "", releaseType: "single", releaseDate: "", coverUrl: "", description: "" })
        mutate(`/api/artist/releases?artistId=${artistId}`)
      }
    } catch (error) {
      toast({ title: "Erreur lors de la planification", variant: "destructive" })
    }
  }

  const handleDeleteRelease = async () => {
    if (!selectedRelease) return

    try {
      const response = await fetch(`/api/artist/releases?id=${selectedRelease.id}`, {
        method: "DELETE",
      })

      if (response.ok) {
        toast({ title: "Sortie annulee" })
        setShowDeleteDialog(false)
        setSelectedRelease(null)
        mutate(`/api/artist/releases?artistId=${artistId}`)
      }
    } catch (error) {
      toast({ title: "Erreur lors de l'annulation", variant: "destructive" })
    }
  }

  const getDaysUntilRelease = (date: string) => {
    const releaseDate = new Date(date)
    const today = new Date()
    const diffTime = releaseDate.getTime() - today.getTime()
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    return diffDays
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="w-8 h-8 animate-spin text-purple-500" />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white">Sorties</h1>
          <p className="text-zinc-400">Gerez vos sorties planifiees et passees</p>
        </div>
        <Button onClick={() => setShowNewRelease(true)} className="bg-purple-600 hover:bg-purple-700">
          <Plus className="w-4 h-4 mr-2" />
          Planifier une sortie
        </Button>
      </div>

      {/* Upcoming Releases */}
      <Card className="bg-zinc-800/30 border-zinc-700/50">
        <CardHeader>
          <CardTitle className="text-white flex items-center gap-2">
            <Calendar className="w-5 h-5 text-purple-400" />
            Sorties a venir ({upcomingReleases.length})
          </CardTitle>
        </CardHeader>
        <CardContent>
          {upcomingReleases.length > 0 ? (
            <div className="space-y-4">
              {upcomingReleases.map((release: any) => {
                const daysUntil = getDaysUntilRelease(release.release_date)
                return (
                  <div
                    key={release.id}
                    className="flex items-center gap-4 p-4 bg-zinc-900/50 rounded-lg border border-zinc-700/50"
                  >
                    <img
                      src={release.cover_url || "/placeholder.svg?height=64&width=64&query=album cover"}
                      alt={release.title}
                      className="w-16 h-16 rounded-lg object-cover"
                    />
                    <div className="flex-1 min-w-0">
                      <h3 className="text-white font-medium">{release.title}</h3>
                      <div className="flex items-center gap-2 mt-1">
                        {getTypeBadge(release.release_type)}
                        {getStatusBadge(release.status)}
                      </div>
                      <p className="text-zinc-400 text-sm mt-1">
                        Sortie le {new Date(release.release_date).toLocaleDateString("fr-FR")}
                      </p>
                    </div>
                    <div className="text-right hidden sm:block">
                      <p className="text-2xl font-bold text-purple-400">{daysUntil}</p>
                      <p className="text-zinc-400 text-sm">jours</p>
                    </div>
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button variant="ghost" size="icon" className="text-zinc-400 hover:text-white">
                          <MoreHorizontal className="w-4 h-4" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end" className="bg-zinc-800 border-zinc-700">
                        <DropdownMenuItem className="text-zinc-300">
                          <Eye className="w-4 h-4 mr-2" /> Voir
                        </DropdownMenuItem>
                        <DropdownMenuItem className="text-zinc-300">
                          <Edit className="w-4 h-4 mr-2" /> Modifier
                        </DropdownMenuItem>
                        <DropdownMenuSeparator className="bg-zinc-700" />
                        <DropdownMenuItem
                          onClick={() => {
                            setSelectedRelease(release)
                            setShowDeleteDialog(true)
                          }}
                          className="text-red-400"
                        >
                          <Trash2 className="w-4 h-4 mr-2" /> Annuler
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </div>
                )
              })}
            </div>
          ) : (
            <div className="text-center py-8 text-zinc-400">
              <Calendar className="w-12 h-12 mx-auto mb-2 opacity-50" />
              <p>Aucune sortie planifiee</p>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Past Releases */}
      <Card className="bg-zinc-800/30 border-zinc-700/50">
        <CardHeader>
          <CardTitle className="text-white flex items-center gap-2">
            <CheckCircle className="w-5 h-5 text-green-400" />
            Sorties passees ({pastReleases.length})
          </CardTitle>
        </CardHeader>
        <CardContent>
          {pastReleases.length > 0 ? (
            <div className="space-y-4">
              {pastReleases.map((release: any) => (
                <div
                  key={release.id}
                  className="flex items-center gap-4 p-4 bg-zinc-900/50 rounded-lg border border-zinc-700/50"
                >
                  <img
                    src={release.cover_url || "/placeholder.svg?height=64&width=64&query=album cover"}
                    alt={release.title}
                    className="w-16 h-16 rounded-lg object-cover"
                  />
                  <div className="flex-1 min-w-0">
                    <h3 className="text-white font-medium">{release.title}</h3>
                    <div className="flex items-center gap-2 mt-1">
                      {getTypeBadge(release.release_type)}
                      {getStatusBadge(release.status)}
                    </div>
                    <p className="text-zinc-400 text-sm mt-1">
                      Sorti le {new Date(release.release_date).toLocaleDateString("fr-FR")}
                    </p>
                  </div>
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button variant="ghost" size="icon" className="text-zinc-400 hover:text-white">
                        <MoreHorizontal className="w-4 h-4" />
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end" className="bg-zinc-800 border-zinc-700">
                      <DropdownMenuItem className="text-zinc-300">
                        <Eye className="w-4 h-4 mr-2" /> Voir les stats
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-8 text-zinc-400">
              <CheckCircle className="w-12 h-12 mx-auto mb-2 opacity-50" />
              <p>Aucune sortie passee</p>
            </div>
          )}
        </CardContent>
      </Card>

      {/* New Release Dialog */}
      <Dialog open={showNewRelease} onOpenChange={setShowNewRelease}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Planifier une sortie</DialogTitle>
            <DialogDescription className="text-zinc-400">Programmez la sortie d'un nouveau titre</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            {/* Cover Upload */}
            <div className="space-y-2">
              <Label>Couverture</Label>
              <div className="flex items-center gap-4">
                {newRelease.coverUrl ? (
                  <img
                    src={newRelease.coverUrl || "/placeholder.svg"}
                    alt="Cover"
                    className="w-20 h-20 rounded-lg object-cover"
                  />
                ) : (
                  <div className="w-20 h-20 bg-zinc-800 rounded-lg flex items-center justify-center">
                    <Upload className="w-6 h-6 text-zinc-500" />
                  </div>
                )}
                <div>
                  <input
                    type="file"
                    id="cover-upload"
                    accept="image/*"
                    onChange={handleCoverUpload}
                    className="hidden"
                  />
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    className="border-zinc-700 bg-transparent"
                    onClick={() => document.getElementById("cover-upload")?.click()}
                    disabled={uploading}
                  >
                    {uploading ? <Loader2 className="w-4 h-4 animate-spin" /> : "Choisir une image"}
                  </Button>
                </div>
              </div>
            </div>

            <div className="space-y-2">
              <Label>Titre</Label>
              <Input
                value={newRelease.title}
                onChange={(e) => setNewRelease({ ...newRelease, title: e.target.value })}
                className="bg-zinc-800 border-zinc-700"
                placeholder="Nom de la sortie"
              />
            </div>
            <div className="space-y-2">
              <Label>Type</Label>
              <Select
                value={newRelease.releaseType}
                onValueChange={(value) => setNewRelease({ ...newRelease, releaseType: value })}
              >
                <SelectTrigger className="bg-zinc-800 border-zinc-700">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent className="bg-zinc-800 border-zinc-700">
                  <SelectItem value="single">Single</SelectItem>
                  <SelectItem value="ep">EP</SelectItem>
                  <SelectItem value="album">Album</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Date de sortie</Label>
              <Input
                type="date"
                value={newRelease.releaseDate}
                onChange={(e) => setNewRelease({ ...newRelease, releaseDate: e.target.value })}
                className="bg-zinc-800 border-zinc-700"
              />
            </div>
            <div className="space-y-2">
              <Label>Description (optionnel)</Label>
              <Textarea
                value={newRelease.description}
                onChange={(e) => setNewRelease({ ...newRelease, description: e.target.value })}
                className="bg-zinc-800 border-zinc-700"
                placeholder="Description de la sortie..."
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowNewRelease(false)}>
              Annuler
            </Button>
            <Button
              className="bg-purple-600 hover:bg-purple-700"
              onClick={handleCreateRelease}
              disabled={!newRelease.title || !newRelease.releaseDate}
            >
              Planifier
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Dialog */}
      <Dialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Annuler la sortie</DialogTitle>
            <DialogDescription className="text-zinc-400">
              Etes-vous sur de vouloir annuler la sortie "{selectedRelease?.title}" ?
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowDeleteDialog(false)}>
              Non, garder
            </Button>
            <Button variant="destructive" onClick={handleDeleteRelease}>
              Oui, annuler
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
