"use client"

import { useState } from "react"
import { DollarSign, CreditCard, Users, Download, Loader2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import useSWR from "swr"

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

export default function AdminRevenuePage() {
  const [period, setPeriod] = useState("12m")

  const { data, isLoading } = useSWR("/api/admin/revenue", fetcher)

  const formatCurrency = (amount: number) => {
    if (amount >= 1000000000) return `${(amount / 1000000000).toFixed(1)}Mrd FCFA`
    if (amount >= 1000000) return `${(amount / 1000000).toFixed(1)}M FCFA`
    if (amount >= 1000) return `${(amount / 1000).toFixed(1)}K FCFA`
    return amount.toLocaleString() + " FCFA"
  }

  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 totalRevenue = data?.totalRevenue || 0
  const subscriptionBreakdown = data?.subscriptionBreakdown || []
  const recentTransactions = data?.recentTransactions || []
  const monthlyRevenue = data?.monthlyRevenue || []

  const totalSubscriptions = subscriptionBreakdown.reduce(
    (sum: number, s: any) => sum + Number.parseInt(s.users || 0),
    0,
  )
  const maxRevenue =
    monthlyRevenue.length > 0 ? Math.max(...monthlyRevenue.map((d: any) => Number.parseInt(d.revenue || 0))) : 1

  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">Revenus</h1>
          <p className="text-zinc-400 text-sm">Analyse des revenus et abonnements</p>
        </div>
        <div className="flex items-center gap-3">
          <Select value={period} onValueChange={setPeriod}>
            <SelectTrigger className="w-40 bg-zinc-800/50 border-zinc-700 text-white">
              <SelectValue />
            </SelectTrigger>
            <SelectContent className="bg-zinc-800 border-zinc-700">
              <SelectItem value="7d">7 derniers jours</SelectItem>
              <SelectItem value="30d">30 derniers jours</SelectItem>
              <SelectItem value="12m">12 derniers mois</SelectItem>
            </SelectContent>
          </Select>
          <Button variant="outline" className="border-zinc-700 text-zinc-300 bg-transparent">
            <Download className="w-4 h-4 mr-2" />
            Exporter
          </Button>
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium text-zinc-400">Revenus Total</CardTitle>
            <DollarSign className="w-4 h-4 text-green-400" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-white">{formatCurrency(totalRevenue)}</div>
          </CardContent>
        </Card>
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium text-zinc-400">Abonnes</CardTitle>
            <CreditCard className="w-4 h-4 text-purple-400" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-white">{totalSubscriptions.toLocaleString()}</div>
          </CardContent>
        </Card>
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium text-zinc-400">Plans</CardTitle>
            <Users className="w-4 h-4 text-blue-400" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-white">{subscriptionBreakdown.length}</div>
          </CardContent>
        </Card>
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium text-zinc-400">ARPU</CardTitle>
            <DollarSign className="w-4 h-4 text-yellow-400" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-white">
              {totalSubscriptions > 0 ? formatCurrency(Math.round(totalRevenue / totalSubscriptions)) : "0 FCFA"}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Revenue Chart */}
      <Card className="bg-zinc-800/30 border-zinc-700/50">
        <CardHeader>
          <CardTitle className="text-white">Evolution des revenus</CardTitle>
          <CardDescription className="text-zinc-400">Revenus mensuels</CardDescription>
        </CardHeader>
        <CardContent>
          {monthlyRevenue.length === 0 ? (
            <div className="h-72 flex items-center justify-center text-zinc-400">Pas de donnees disponibles</div>
          ) : (
            <div className="h-72 flex items-end gap-2">
              {monthlyRevenue.map((data: any, index: number) => (
                <div key={index} className="flex-1 flex flex-col items-center gap-2">
                  <div
                    className="w-full bg-purple-600 rounded-t"
                    style={{ height: `${(Number.parseInt(data.revenue || 0) / maxRevenue) * 240}px`, minHeight: "4px" }}
                  />
                  <span className="text-xs text-zinc-400">{data.month}</span>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Bottom Row */}
      <div className="grid gap-6 lg:grid-cols-2">
        {/* Subscription Breakdown */}
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardHeader>
            <CardTitle className="text-white">Repartition abonnements</CardTitle>
            <CardDescription className="text-zinc-400">
              {totalSubscriptions.toLocaleString()} abonnes au total
            </CardDescription>
          </CardHeader>
          <CardContent>
            {subscriptionBreakdown.length === 0 ? (
              <p className="text-zinc-400 text-center py-4">Aucun abonnement</p>
            ) : (
              <div className="space-y-4">
                {subscriptionBreakdown.map((sub: any, index: number) => {
                  const colors = ["bg-purple-500", "bg-blue-500", "bg-cyan-500", "bg-zinc-500"]
                  return (
                    <div key={index} className="space-y-2">
                      <div className="flex items-center justify-between">
                        <span className="text-white font-medium">{sub.plan}</span>
                        <span className="text-zinc-400">
                          {Number.parseInt(sub.users || 0).toLocaleString()} utilisateurs
                        </span>
                      </div>
                      <div className="flex items-center gap-3">
                        <div className="flex-1 h-3 bg-zinc-700 rounded-full overflow-hidden">
                          <div
                            className={`h-full ${colors[index % colors.length]} rounded-full`}
                            style={{ width: `${(Number.parseInt(sub.users || 0) / totalSubscriptions) * 100}%` }}
                          />
                        </div>
                        <span className="text-sm text-zinc-300 w-24 text-right">
                          {formatCurrency(Number.parseInt(sub.revenue || 0))}
                        </span>
                      </div>
                    </div>
                  )
                })}
              </div>
            )}
          </CardContent>
        </Card>

        {/* Recent Transactions */}
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardHeader>
            <CardTitle className="text-white">Transactions recentes</CardTitle>
            <CardDescription className="text-zinc-400">Dernieres transactions</CardDescription>
          </CardHeader>
          <CardContent>
            {recentTransactions.length === 0 ? (
              <p className="text-zinc-400 text-center py-4">Aucune transaction</p>
            ) : (
              <div className="space-y-4">
                {recentTransactions.map((tx: any) => (
                  <div key={tx.id} className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <div className="w-10 h-10 bg-purple-500/20 rounded-full flex items-center justify-center">
                        <CreditCard className="w-5 h-5 text-purple-400" />
                      </div>
                      <div>
                        <p className="font-medium text-white">{tx.user}</p>
                        <p className="text-sm text-zinc-400">{tx.type || "Paiement"}</p>
                      </div>
                    </div>
                    <div className="text-right">
                      <p className="font-medium text-white">{formatCurrency(tx.amount)}</p>
                      {tx.status === "completed" ? (
                        <Badge className="bg-green-500/20 text-green-400 border-0">Complete</Badge>
                      ) : (
                        <Badge className="bg-yellow-500/20 text-yellow-400 border-0">En attente</Badge>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
