"use client"
import { ArrowLeft, ShoppingBag, Music, Disc, FileText } from "lucide-react"
import Link from "next/link"
import useSWR from "swr"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { useAuth } from "@/components/auth-provider"

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

export default function PurchasesPage() {
  const { user } = useAuth()
  const { data, isLoading } = useSWR("/api/purchases", fetcher)

  const purchases = data?.purchases || []
  const stats = data?.stats || { total_purchases: 0, total_spent: 0, tracks_purchased: 0, albums_purchased: 0 }

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat("fr-FR", {
      style: "currency",
      currency: "XOF",
      minimumFractionDigits: 0,
    }).format(amount)
  }

  const formatDate = (date: string) => {
    return new Date(date).toLocaleDateString("fr-FR", {
      day: "2-digit",
      month: "short",
      year: "numeric",
    })
  }

  const getStatusBadge = (status: string) => {
    switch (status) {
      case "completed":
        return <Badge className="bg-green-500/20 text-green-400 border-0">Complété</Badge>
      case "pending":
        return <Badge className="bg-yellow-500/20 text-yellow-400 border-0">En attente</Badge>
      case "failed":
        return <Badge className="bg-red-500/20 text-red-400 border-0">Échoué</Badge>
      case "refunded":
        return <Badge className="bg-zinc-500/20 text-zinc-400 border-0">Remboursé</Badge>
      default:
        return null
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-b from-zinc-900 to-black text-white pb-24">
      <div className="max-w-6xl mx-auto px-4 py-8">
        {/* Header */}
        <div className="flex items-center gap-4 mb-8">
          <Link href="/profile">
            <Button variant="ghost" size="icon" className="text-zinc-400 hover:text-white">
              <ArrowLeft className="w-5 h-5" />
            </Button>
          </Link>
          <div>
            <h1 className="text-2xl font-bold">Historique d'achats</h1>
            <p className="text-zinc-400">Consultez tous vos achats de titres et albums</p>
          </div>
        </div>

        {/* Stats Cards */}
        <div className="grid md:grid-cols-4 gap-4 mb-8">
          <Card className="bg-zinc-800/30 border-zinc-700/50">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-zinc-400 text-sm">Total dépensé</p>
                  <p className="text-2xl font-bold text-white">{formatCurrency(stats.total_spent || 0)}</p>
                </div>
                <ShoppingBag className="w-10 h-10 text-green-400 opacity-50" />
              </div>
            </CardContent>
          </Card>

          <Card className="bg-zinc-800/30 border-zinc-700/50">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-zinc-400 text-sm">Achats totaux</p>
                  <p className="text-2xl font-bold text-white">{stats.total_purchases || 0}</p>
                </div>
                <FileText className="w-10 h-10 text-blue-400 opacity-50" />
              </div>
            </CardContent>
          </Card>

          <Card className="bg-zinc-800/30 border-zinc-700/50">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-zinc-400 text-sm">Titres achetés</p>
                  <p className="text-2xl font-bold text-white">{stats.tracks_purchased || 0}</p>
                </div>
                <Music className="w-10 h-10 text-purple-400 opacity-50" />
              </div>
            </CardContent>
          </Card>

          <Card className="bg-zinc-800/30 border-zinc-700/50">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-zinc-400 text-sm">Albums achetés</p>
                  <p className="text-2xl font-bold text-white">{stats.albums_purchased || 0}</p>
                </div>
                <Disc className="w-10 h-10 text-pink-400 opacity-50" />
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Purchases List */}
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardHeader>
            <CardTitle className="text-white">Tous les achats</CardTitle>
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="text-center py-12 text-zinc-400">Chargement...</div>
            ) : purchases.length === 0 ? (
              <div className="text-center py-12">
                <ShoppingBag className="w-16 h-16 mx-auto mb-4 text-zinc-600" />
                <p className="text-zinc-400 mb-2">Aucun achat pour le moment</p>
                <p className="text-zinc-500 text-sm">Commencez à acheter des titres et albums</p>
              </div>
            ) : (
              <div className="space-y-3">
                {purchases.map((purchase: any) => (
                  <div
                    key={purchase.id}
                    className="flex items-center gap-4 p-4 bg-zinc-900/50 rounded-lg hover:bg-zinc-900/70 transition"
                  >
                    <img
                      src={purchase.item_cover || "/placeholder.svg?height=60&width=60"}
                      alt={purchase.item_title}
                      className="w-14 h-14 rounded object-cover"
                    />
                    <div className="flex-1 min-w-0">
                      <h3 className="text-white font-medium truncate">{purchase.item_title}</h3>
                      <p className="text-zinc-400 text-sm">{purchase.artist_name}</p>
                      <div className="flex items-center gap-2 mt-1">
                        <Badge variant="outline" className="text-xs">
                          {purchase.purchase_type === "track" ? (
                            <Music className="w-3 h-3 mr-1" />
                          ) : (
                            <Disc className="w-3 h-3 mr-1" />
                          )}
                          {purchase.purchase_type === "track" ? "Titre" : "Album"}
                        </Badge>
                        <span className="text-zinc-500 text-xs">{formatDate(purchase.created_at)}</span>
                      </div>
                    </div>
                    <div className="text-right">
                      <p className="text-white font-semibold">{formatCurrency(purchase.price_fcfa)}</p>
                      <p className="text-zinc-500 text-xs mt-1">{purchase.payment_method || "Carte"}</p>
                    </div>
                    {getStatusBadge(purchase.status)}
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
