"use client"

import { useState } from "react"
import {
  DollarSign,
  TrendingUp,
  Download,
  CreditCard,
  Calendar,
  ArrowUpRight,
  ArrowDownRight,
  Clock,
  FileText,
  Loader2,
} from "lucide-react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Badge } from "@/components/ui/badge"
import { useAuth } from "@/components/auth-provider"
import { useToast } from "@/hooks/use-toast"
import useSWR from "swr"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"

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

export default function ArtistEarningsPage() {
  const { user } = useAuth()
  const { toast } = useToast()
  const artistId = user?.artistId
  const [period, setPeriod] = useState(new Date().getFullYear().toString())
  const [showWithdrawDialog, setShowWithdrawDialog] = useState(false)
  const [withdrawAmount, setWithdrawAmount] = useState("")

  const { data, isLoading, mutate } = useSWR(
    artistId ? `/api/artist/earnings?artistId=${artistId}&year=${period}` : null,
    fetcher,
  )

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat("fr-FR").format(amount) + " 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()
  }

  const handleWithdraw = async () => {
    try {
      const response = await fetch("/api/artist/earnings", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          artistId,
          amount: Number.parseInt(withdrawAmount),
          paymentMethod: "mobile_money",
        }),
      })

      if (response.ok) {
        toast({ title: "Demande de retrait envoyee" })
        setShowWithdrawDialog(false)
        setWithdrawAmount("")
        mutate()
      }
    } catch (error) {
      toast({ title: "Erreur lors de la demande", 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>
    )
  }

  const {
    earningsHistory = [],
    availableBalance = 0,
    currentMonthEarnings = 0,
    pendingAmount = 0,
    totalYearEarnings = 0,
    percentChange = 0,
    breakdown = [],
  } = data || {}

  // Calculate total percentage for breakdown
  const totalBreakdown = breakdown.reduce((acc: number, item: any) => acc + item.amount, 0)

  return (
    <div className="space-y-6">
      {/* Header */}
      <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">Revenus</h1>
          <p className="text-zinc-400">Suivez vos gains</p>
        </div>
        <div className="flex items-center gap-3">
          <Select value={period} onValueChange={setPeriod}>
            <SelectTrigger className="w-32 bg-zinc-800/50 border-zinc-700 text-white">
              <SelectValue />
            </SelectTrigger>
            <SelectContent className="bg-zinc-800 border-zinc-700">
              <SelectItem value="2024">2024</SelectItem>
              <SelectItem value="2023">2023</SelectItem>
              <SelectItem value="all">Tout</SelectItem>
            </SelectContent>
          </Select>
          <Button variant="outline" className="border-zinc-700 text-zinc-300 hover:text-white bg-transparent">
            <Download className="w-4 h-4 mr-2" />
            Exporter
          </Button>
        </div>
      </div>

      {/* Overview Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <Card className="bg-gradient-to-br from-purple-600/20 to-pink-600/20 border-purple-500/30">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-zinc-300 text-sm">Solde disponible</p>
                <p className="text-3xl font-bold text-white mt-1">{formatCurrency(availableBalance)}</p>
              </div>
              <div className="w-12 h-12 bg-white/10 rounded-xl flex items-center justify-center">
                <DollarSign className="w-6 h-6 text-white" />
              </div>
            </div>
            <Button
              className="w-full mt-4 bg-white/20 hover:bg-white/30 text-white"
              onClick={() => setShowWithdrawDialog(true)}
              disabled={availableBalance <= 0}
            >
              <CreditCard className="w-4 h-4 mr-2" />
              Retirer
            </Button>
          </CardContent>
        </Card>

        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-zinc-400 text-sm">Ce mois</p>
                <p className="text-2xl font-bold text-white mt-1">{formatCurrency(currentMonthEarnings)}</p>
                {percentChange !== 0 && (
                  <p
                    className={`${percentChange > 0 ? "text-green-400" : "text-red-400"} text-xs flex items-center mt-1`}
                  >
                    {percentChange > 0 ? (
                      <ArrowUpRight className="w-3 h-3 mr-1" />
                    ) : (
                      <ArrowDownRight className="w-3 h-3 mr-1" />
                    )}
                    {percentChange > 0 ? "+" : ""}
                    {percentChange}%
                  </p>
                )}
              </div>
              <div className="w-12 h-12 bg-green-500/20 rounded-xl flex items-center justify-center">
                <TrendingUp className="w-6 h-6 text-green-400" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-zinc-400 text-sm">En attente</p>
                <p className="text-2xl font-bold text-white mt-1">{formatCurrency(pendingAmount)}</p>
                <p className="text-zinc-400 text-xs flex items-center mt-1">
                  <Clock className="w-3 h-3 mr-1" />
                  Prochain paiement: 15 Jan
                </p>
              </div>
              <div className="w-12 h-12 bg-yellow-500/20 rounded-xl flex items-center justify-center">
                <Clock className="w-6 h-6 text-yellow-400" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-zinc-400 text-sm">Total {period}</p>
                <p className="text-2xl font-bold text-white mt-1">{formatCurrency(totalYearEarnings)}</p>
              </div>
              <div className="w-12 h-12 bg-purple-500/20 rounded-xl flex items-center justify-center">
                <Calendar className="w-6 h-6 text-purple-400" />
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      <div className="grid lg:grid-cols-3 gap-6">
        {/* Revenue Breakdown */}
        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardHeader>
            <CardTitle className="text-white">Repartition par titre</CardTitle>
          </CardHeader>
          <CardContent>
            {breakdown.length === 0 ? (
              <p className="text-zinc-400 text-center py-4">Pas de donnees disponibles</p>
            ) : (
              <div className="space-y-4">
                {breakdown.map((item: any, index: number) => {
                  const percentage = totalBreakdown > 0 ? Math.round((item.amount / totalBreakdown) * 100) : 0
                  return (
                    <div key={index} className="space-y-2">
                      <div className="flex items-center justify-between">
                        <span className="text-zinc-300 truncate">{item.source}</span>
                        <span className="text-white font-medium">{formatCurrency(item.amount)}</span>
                      </div>
                      <div className="h-2 bg-zinc-700 rounded-full overflow-hidden">
                        <div
                          className="h-full bg-gradient-to-r from-purple-600 to-pink-500 rounded-full"
                          style={{ width: `${percentage}%` }}
                        ></div>
                      </div>
                    </div>
                  )
                })}
              </div>
            )}
          </CardContent>
        </Card>

        {/* Earnings History */}
        <Card className="bg-zinc-800/50 border-zinc-700 lg:col-span-2">
          <CardHeader className="flex flex-row items-center justify-between">
            <CardTitle className="text-white">Historique</CardTitle>
            <Button variant="ghost" size="sm" className="text-zinc-400 hover:text-white">
              <FileText className="w-4 h-4 mr-2" />
              Factures
            </Button>
          </CardHeader>
          <CardContent>
            {earningsHistory.length === 0 ? (
              <p className="text-zinc-400 text-center py-8">Aucun historique de revenus</p>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead>
                    <tr className="border-b border-zinc-700">
                      <th className="text-left text-zinc-400 text-sm font-medium pb-3">Periode</th>
                      <th className="text-left text-zinc-400 text-sm font-medium pb-3">Streams</th>
                      <th className="text-left text-zinc-400 text-sm font-medium pb-3">Revenus</th>
                      <th className="text-left text-zinc-400 text-sm font-medium pb-3">Statut</th>
                    </tr>
                  </thead>
                  <tbody>
                    {earningsHistory.map((row: any, index: number) => (
                      <tr key={index} className="border-b border-zinc-700/50">
                        <td className="py-4 text-white">{row.month}</td>
                        <td className="py-4 text-zinc-300">{formatNumber(row.streams)}</td>
                        <td className="py-4 text-white font-medium">{formatCurrency(row.earnings)}</td>
                        <td className="py-4">
                          {row.status === "paid" ? (
                            <Badge className="bg-green-500/20 text-green-400 border-0">Paye</Badge>
                          ) : row.status === "approved" ? (
                            <Badge className="bg-blue-500/20 text-blue-400 border-0">Approuve</Badge>
                          ) : (
                            <Badge className="bg-yellow-500/20 text-yellow-400 border-0">En attente</Badge>
                          )}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Withdraw Dialog */}
      <Dialog open={showWithdrawDialog} onOpenChange={setShowWithdrawDialog}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Demande de retrait</DialogTitle>
            <DialogDescription className="text-zinc-400">
              Solde disponible: {formatCurrency(availableBalance)}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Montant (FCFA)</Label>
              <Input
                type="number"
                className="bg-zinc-800 border-zinc-700"
                placeholder="Ex: 50000"
                value={withdrawAmount}
                onChange={(e) => setWithdrawAmount(e.target.value)}
                max={availableBalance}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowWithdrawDialog(false)}>
              Annuler
            </Button>
            <Button
              className="bg-purple-600 hover:bg-purple-700"
              onClick={handleWithdraw}
              disabled={
                !withdrawAmount ||
                Number.parseInt(withdrawAmount) <= 0 ||
                Number.parseInt(withdrawAmount) > availableBalance
              }
            >
              Demander le retrait
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
