"use client"

import type React from "react"

import { useState } from "react"
import useSWR from "swr"
import {
  Search,
  DollarSign,
  TrendingUp,
  Users,
  Clock,
  Download,
  MoreHorizontal,
  CheckCircle,
  AlertCircle,
  Loader2,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { useToast } from "@/hooks/use-toast"

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

export default function AdminRoyaltiesPage() {
  const { toast } = useToast()
  const { data, error, isLoading, mutate } = useSWR("/api/admin/royalties", fetcher)
  const payouts = data?.payouts || []
  const stats = data?.stats || { totalPaid: 0, totalPending: 0, artistCount: 0, avgRate: 0 }
  const rates = data?.rates || []

  const [searchQuery, setSearchQuery] = useState("")
  const [statusFilter, setStatusFilter] = useState("all")
  const [showPayoutDialog, setShowPayoutDialog] = useState(false)
  const [isProcessing, setIsProcessing] = useState(false)

  const filteredPayouts = payouts.filter((payout: any) => {
    const matchesSearch = payout.artist_name?.toLowerCase().includes(searchQuery.toLowerCase())
    const matchesStatus = statusFilter === "all" || payout.status === statusFilter
    return matchesSearch && matchesStatus
  })

  const formatCurrency = (num: number) => {
    return new Intl.NumberFormat("fr-FR").format(num) + " FCFA"
  }

  const formatNumber = (num: number) => {
    if (num >= 1000000) return `${(num / 1000000).toFixed(1)}M`
    if (num >= 1000) return `${(num / 1000).toFixed(1)}K`
    return num?.toString() || "0"
  }

  const getStatusBadge = (status: string) => {
    const statuses: Record<string, { color: string; label: string; icon: React.ReactNode }> = {
      paid: { color: "bg-green-500/20 text-green-400", label: "Payé", icon: <CheckCircle className="w-3 h-3" /> },
      pending: { color: "bg-yellow-500/20 text-yellow-400", label: "En attente", icon: <Clock className="w-3 h-3" /> },
      processing: {
        color: "bg-blue-500/20 text-blue-400",
        label: "En cours",
        icon: <TrendingUp className="w-3 h-3" />,
      },
      threshold: {
        color: "bg-zinc-500/20 text-zinc-400",
        label: "Seuil non atteint",
        icon: <AlertCircle className="w-3 h-3" />,
      },
    }
    const s = statuses[status] || { color: "bg-zinc-500/20 text-zinc-400", label: status, icon: null }
    return (
      <Badge className={`${s.color} border-0 flex items-center gap-1`}>
        {s.icon}
        {s.label}
      </Badge>
    )
  }

  const handleProcessPayouts = async () => {
    setIsProcessing(true)
    try {
      const res = await fetch("/api/admin/royalties/process", { method: "POST" })
      if (res.ok) {
        toast({ title: "Paiements lancés avec succès" })
        mutate()
      }
    } catch (e) {
      toast({ title: "Erreur", variant: "destructive" })
    }
    setIsProcessing(false)
    setShowPayoutDialog(false)
  }

  const handlePayNow = async (payoutId: string) => {
    try {
      const res = await fetch(`/api/admin/royalties/${payoutId}/pay`, { method: "POST" })
      if (res.ok) {
        toast({ title: "Paiement effectué" })
        mutate()
      }
    } catch (e) {
      toast({ title: "Erreur", variant: "destructive" })
    }
  }

  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">
      {/* Header */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Royalties</h1>
          <p className="text-zinc-400 text-sm">Gestion des paiements artistes</p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" className="border-zinc-700 text-zinc-300 bg-transparent">
            <Download className="w-4 h-4 mr-2" />
            Exporter
          </Button>
          <Button onClick={() => setShowPayoutDialog(true)} className="bg-purple-600 hover:bg-purple-700">
            <DollarSign className="w-4 h-4 mr-2" />
            Lancer les paiements
          </Button>
        </div>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-green-500/20">
              <DollarSign className="w-5 h-5 text-green-400" />
            </div>
            <div>
              <p className="text-xl font-bold text-white">{formatCurrency(stats.totalPaid)}</p>
              <p className="text-zinc-400 text-sm">Payés ce mois</p>
            </div>
          </div>
        </div>
        <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-yellow-500/20">
              <Clock className="w-5 h-5 text-yellow-400" />
            </div>
            <div>
              <p className="text-xl font-bold text-white">{formatCurrency(stats.totalPending)}</p>
              <p className="text-zinc-400 text-sm">En attente</p>
            </div>
          </div>
        </div>
        <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-purple-500/20">
              <Users className="w-5 h-5 text-purple-400" />
            </div>
            <div>
              <p className="text-xl font-bold text-white">{stats.artistCount}</p>
              <p className="text-zinc-400 text-sm">Artistes</p>
            </div>
          </div>
        </div>
        <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
          <div className="flex items-center gap-3">
            <div className="p-2 rounded-lg bg-blue-500/20">
              <TrendingUp className="w-5 h-5 text-blue-400" />
            </div>
            <div>
              <p className="text-xl font-bold text-white">{stats.avgRate} FCFA</p>
              <p className="text-zinc-400 text-sm">Taux moyen/stream</p>
            </div>
          </div>
        </div>
      </div>

      <Tabs defaultValue="payouts" className="space-y-4">
        <TabsList className="bg-zinc-800/50 border border-zinc-700/50">
          <TabsTrigger value="payouts" className="data-[state=active]:bg-purple-600">
            Paiements
          </TabsTrigger>
          <TabsTrigger value="rates" className="data-[state=active]:bg-purple-600">
            Taux
          </TabsTrigger>
        </TabsList>

        <TabsContent value="payouts" className="space-y-4">
          <div className="flex flex-col gap-4 sm:flex-row">
            <div className="relative flex-1 max-w-md">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-400" />
              <Input
                placeholder="Rechercher un artiste..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-10 bg-zinc-800/50 border-zinc-700 text-white"
              />
            </div>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-40 bg-zinc-800/50 border-zinc-700 text-white">
                <SelectValue placeholder="Statut" />
              </SelectTrigger>
              <SelectContent className="bg-zinc-800 border-zinc-700">
                <SelectItem value="all">Tous</SelectItem>
                <SelectItem value="paid">Payés</SelectItem>
                <SelectItem value="pending">En attente</SelectItem>
                <SelectItem value="processing">En cours</SelectItem>
                <SelectItem value="threshold">Seuil non atteint</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {payouts.length === 0 ? (
            <div className="text-center py-16 bg-zinc-800/50 rounded-xl border border-zinc-700/50">
              <DollarSign className="w-16 h-16 mx-auto mb-4 text-zinc-600" />
              <h3 className="text-xl font-medium text-white mb-2">Aucun paiement</h3>
              <p className="text-zinc-400">Les paiements apparaîtront ici une fois générés</p>
            </div>
          ) : (
            <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 overflow-hidden">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-zinc-700/50">
                    <th className="p-4 text-left text-sm font-medium text-zinc-400">Artiste</th>
                    <th className="p-4 text-left text-sm font-medium text-zinc-400 hidden md:table-cell">Période</th>
                    <th className="p-4 text-left text-sm font-medium text-zinc-400 hidden lg:table-cell">Streams</th>
                    <th className="p-4 text-left text-sm font-medium text-zinc-400">Montant</th>
                    <th className="p-4 text-left text-sm font-medium text-zinc-400">Statut</th>
                    <th className="p-4 text-right text-sm font-medium text-zinc-400">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {filteredPayouts.map((payout: any) => (
                    <tr key={payout.id} className="border-b border-zinc-700/30 hover:bg-zinc-700/20 transition-colors">
                      <td className="p-4">
                        <div className="flex items-center gap-3">
                          <img
                            src={payout.artist_avatar || "/placeholder.svg?height=40&width=40&query=artist"}
                            alt={payout.artist_name}
                            className="w-10 h-10 rounded-full object-cover"
                          />
                          <div>
                            <p className="font-medium text-white">{payout.artist_name}</p>
                            <p className="text-sm text-zinc-400">{payout.id}</p>
                          </div>
                        </div>
                      </td>
                      <td className="p-4 text-zinc-400 hidden md:table-cell">{payout.period || "-"}</td>
                      <td className="p-4 text-zinc-400 hidden lg:table-cell">{formatNumber(payout.streams || 0)}</td>
                      <td className="p-4 text-white font-semibold">{formatCurrency(payout.amount || 0)}</td>
                      <td className="p-4">{getStatusBadge(payout.status)}</td>
                      <td className="p-4 text-right">
                        <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">Voir les détails</DropdownMenuItem>
                            {payout.status === "pending" && (
                              <DropdownMenuItem onClick={() => handlePayNow(payout.id)} className="text-green-400">
                                Payer maintenant
                              </DropdownMenuItem>
                            )}
                            <DropdownMenuItem className="text-zinc-300">Télécharger le relevé</DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </TabsContent>

        <TabsContent value="rates" className="space-y-4">
          <div className="grid md:grid-cols-2 gap-4">
            <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
              <h3 className="font-semibold text-white mb-4">Taux par type d'abonnement</h3>
              <div className="space-y-4">
                {rates.length === 0 ? (
                  <p className="text-zinc-400">Aucun taux configuré</p>
                ) : (
                  rates.map((rate: any) => (
                    <div key={rate.tier}>
                      <div className="flex justify-between text-sm mb-1">
                        <span className="text-white">{rate.tier}</span>
                        <span className="text-zinc-400">
                          {rate.rate} FCFA/stream ({rate.percentage}%)
                        </span>
                      </div>
                      <div className="h-2 bg-zinc-700 rounded-full overflow-hidden">
                        <div
                          className="h-full bg-gradient-to-r from-purple-500 to-pink-500 rounded-full"
                          style={{ width: `${rate.percentage}%` }}
                        />
                      </div>
                    </div>
                  ))
                )}
              </div>
            </div>

            <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
              <h3 className="font-semibold text-white mb-4">Configuration</h3>
              <div className="space-y-4">
                <div className="flex justify-between items-center">
                  <span className="text-zinc-400">Seuil minimum de paiement</span>
                  <span className="text-white font-semibold">32,800 FCFA</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-zinc-400">Fréquence de paiement</span>
                  <span className="text-white font-semibold">Mensuelle</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-zinc-400">Date de paiement</span>
                  <span className="text-white font-semibold">1er du mois</span>
                </div>
                <div className="flex justify-between items-center">
                  <span className="text-zinc-400">Commission plateforme</span>
                  <span className="text-white font-semibold">30%</span>
                </div>
              </div>
            </div>
          </div>
        </TabsContent>
      </Tabs>

      {/* Payout Dialog */}
      <Dialog open={showPayoutDialog} onOpenChange={setShowPayoutDialog}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Lancer les paiements</DialogTitle>
            <DialogDescription className="text-zinc-400">
              Confirmer le traitement des paiements en attente
            </DialogDescription>
          </DialogHeader>
          <div className="py-4 space-y-4">
            <div className="bg-zinc-800/50 rounded-lg p-4">
              <div className="flex justify-between mb-2">
                <span className="text-zinc-400">Nombre d'artistes</span>
                <span className="text-white">{payouts.filter((p: any) => p.status === "pending").length}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-zinc-400">Montant total</span>
                <span className="text-white font-bold">{formatCurrency(stats.totalPending)}</span>
              </div>
            </div>
            <p className="text-sm text-zinc-400">
              Les paiements seront traités sous 2-3 jours ouvrables. Les artistes seront notifiés par email.
            </p>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowPayoutDialog(false)}>
              Annuler
            </Button>
            <Button className="bg-green-600 hover:bg-green-700" onClick={handleProcessPayouts} disabled={isProcessing}>
              {isProcessing ? (
                <Loader2 className="w-4 h-4 animate-spin mr-2" />
              ) : (
                <CheckCircle className="w-4 h-4 mr-2" />
              )}
              Confirmer les paiements
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
