"use client"

import { useState } from "react"
import useSWR from "swr"
import {
  Phone,
  Search,
  Download,
  Building2,
  Users,
  DollarSign,
  Music,
  ChevronLeft,
  ChevronRight,
  CheckCircle,
  Clock,
  XCircle,
} 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 Link from "next/link"

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

export default function RingtoneDownloadsPage() {
  const [searchPhone, setSearchPhone] = useState("")
  const [operatorFilter, setOperatorFilter] = useState("all") // Updated default value to "all"
  const [statusFilter, setStatusFilter] = useState("all") // Updated default value to "all"
  const [page, setPage] = useState(0)
  const limit = 50

  const queryParams = new URLSearchParams()
  if (searchPhone) queryParams.set("phone", searchPhone)
  if (operatorFilter !== "all") queryParams.set("operator", operatorFilter) // Updated condition to exclude "all"
  if (statusFilter !== "all") queryParams.set("status", statusFilter) // Updated condition to exclude "all"
  queryParams.set("limit", limit.toString())
  queryParams.set("offset", (page * limit).toString())

  const { data, isLoading } = useSWR(`/api/admin/ringtone-api/downloads?${queryParams.toString()}`, fetcher, {
    refreshInterval: 30000,
  })
  const { data: operatorsData } = useSWR("/api/admin/ringtone-api", fetcher)

  const downloads = data?.data || []
  const stats = data?.stats || { totalDownloads: 0, uniqueCustomers: 0, totalRevenue: 0, operatorsCount: 0 }
  const meta = data?.meta || { total: 0, limit, offset: 0 }
  const operators = operatorsData?.data || []

  const getStatusBadge = (status: string, deliveryStatus: string) => {
    if (deliveryStatus === "delivered" || deliveryStatus === "confirmed") {
      return (
        <Badge className="bg-green-500/20 text-green-400 border-0">
          <CheckCircle className="w-3 h-3 mr-1" /> Livré
        </Badge>
      )
    }
    if (deliveryStatus === "pending") {
      return (
        <Badge className="bg-yellow-500/20 text-yellow-400 border-0">
          <Clock className="w-3 h-3 mr-1" /> En attente
        </Badge>
      )
    }
    if (deliveryStatus === "failed") {
      return (
        <Badge className="bg-red-500/20 text-red-400 border-0">
          <XCircle className="w-3 h-3 mr-1" /> Échoué
        </Badge>
      )
    }
    return <Badge className="bg-zinc-500/20 text-zinc-400 border-0">{status}</Badge>
  }

  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">Téléchargements Sonneries</h1>
          <p className="text-zinc-400 text-sm">Suivez les téléchargements par numéro de téléphone et opérateur</p>
        </div>
        <Link href="/admin/ringtone-api">
          <Button variant="outline" className="border-zinc-700 bg-transparent">
            Retour à l'API
          </Button>
        </Link>
      </div>

      {/* Stats Cards */}
      <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-blue-500/20">
              <Download className="w-5 h-5 text-blue-400" />
            </div>
            <div>
              <p className="text-xl font-bold text-white">{stats.totalDownloads.toLocaleString()}</p>
              <p className="text-zinc-400 text-sm">Total Téléchargements</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-green-500/20">
              <Users className="w-5 h-5 text-green-400" />
            </div>
            <div>
              <p className="text-xl font-bold text-white">{stats.uniqueCustomers.toLocaleString()}</p>
              <p className="text-zinc-400 text-sm">Clients Uniques</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">
              <DollarSign className="w-5 h-5 text-yellow-400" />
            </div>
            <div>
              <p className="text-xl font-bold text-white">${stats.totalRevenue.toLocaleString()}</p>
              <p className="text-zinc-400 text-sm">Revenus Total</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">
              <Building2 className="w-5 h-5 text-purple-400" />
            </div>
            <div>
              <p className="text-xl font-bold text-white">{stats.operatorsCount}</p>
              <p className="text-zinc-400 text-sm">Opérateurs Actifs</p>
            </div>
          </div>
        </div>
      </div>

      {/* Filters */}
      <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4">
        <div className="flex flex-col md:flex-row gap-4">
          <div className="flex-1 relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-400" />
            <Input
              className="bg-zinc-900 border-zinc-700 pl-10"
              placeholder="Rechercher par numéro de téléphone ou MSISDN..."
              value={searchPhone}
              onChange={(e) => {
                setSearchPhone(e.target.value)
                setPage(0)
              }}
            />
          </div>
          <Select
            value={operatorFilter}
            onValueChange={(v) => {
              setOperatorFilter(v)
              setPage(0)
            }}
          >
            <SelectTrigger className="w-[200px] bg-zinc-900 border-zinc-700">
              <SelectValue placeholder="Tous les opérateurs" />
            </SelectTrigger>
            <SelectContent className="bg-zinc-800 border-zinc-700">
              <SelectItem value="all">Tous les opérateurs</SelectItem> {/* Updated value prop to "all" */}
              {operators.map((op: any) => (
                <SelectItem key={op.id} value={op.id}>
                  {op.company}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Select
            value={statusFilter}
            onValueChange={(v) => {
              setStatusFilter(v)
              setPage(0)
            }}
          >
            <SelectTrigger className="w-[150px] bg-zinc-900 border-zinc-700">
              <SelectValue placeholder="Statut" />
            </SelectTrigger>
            <SelectContent className="bg-zinc-800 border-zinc-700">
              <SelectItem value="all">Tous</SelectItem> {/* Updated value prop to "all" */}
              <SelectItem value="delivered">Livré</SelectItem>
              <SelectItem value="pending">En attente</SelectItem>
              <SelectItem value="failed">Échoué</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* Downloads Table */}
      <div className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-zinc-900/50">
              <tr>
                <th className="text-left text-xs font-medium text-zinc-400 px-4 py-3">Sonnerie</th>
                <th className="text-left text-xs font-medium text-zinc-400 px-4 py-3">Client</th>
                <th className="text-left text-xs font-medium text-zinc-400 px-4 py-3">Opérateur</th>
                <th className="text-left text-xs font-medium text-zinc-400 px-4 py-3">Prix</th>
                <th className="text-left text-xs font-medium text-zinc-400 px-4 py-3">Statut</th>
                <th className="text-left text-xs font-medium text-zinc-400 px-4 py-3">Date</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-zinc-700/50">
              {isLoading ? (
                <tr>
                  <td colSpan={6} className="text-center py-8 text-zinc-400">
                    Chargement...
                  </td>
                </tr>
              ) : downloads.length === 0 ? (
                <tr>
                  <td colSpan={6} className="text-center py-8 text-zinc-400">
                    <Music className="w-12 h-12 mx-auto mb-2 text-zinc-600" />
                    Aucun téléchargement trouvé
                  </td>
                </tr>
              ) : (
                downloads.map((download: any) => (
                  <tr key={download.id} className="hover:bg-zinc-800/30">
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 bg-zinc-700 rounded overflow-hidden">
                          {download.cover_url && (
                            <img
                              src={download.cover_url || "/placeholder.svg"}
                              alt=""
                              className="w-full h-full object-cover"
                            />
                          )}
                        </div>
                        <div>
                          <p className="text-white font-medium text-sm">{download.track_title || "Unknown"}</p>
                          <p className="text-zinc-400 text-xs">{download.artist_name || "Unknown Artist"}</p>
                        </div>
                      </div>
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-2">
                        <Phone className="w-4 h-4 text-zinc-400" />
                        <div>
                          <p className="text-white text-sm font-mono">
                            {download.customer_phone || download.customer_msisdn}
                          </p>
                          {download.subscriber_id && (
                            <p className="text-zinc-500 text-xs">ID: {download.subscriber_id}</p>
                          )}
                        </div>
                      </div>
                    </td>
                    <td className="px-4 py-3">
                      <p className="text-white text-sm">{download.operator_company || download.operator_name}</p>
                      <p className="text-zinc-500 text-xs">{download.api_name}</p>
                    </td>
                    <td className="px-4 py-3">
                      <p className="text-white text-sm">${download.price?.toFixed(2) || "0.00"}</p>
                      <p className="text-zinc-500 text-xs">{download.currency}</p>
                    </td>
                    <td className="px-4 py-3">{getStatusBadge(download.status, download.delivery_status)}</td>
                    <td className="px-4 py-3">
                      <p className="text-white text-sm">{new Date(download.created_at).toLocaleDateString()}</p>
                      <p className="text-zinc-500 text-xs">{new Date(download.created_at).toLocaleTimeString()}</p>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        <div className="flex items-center justify-between px-4 py-3 border-t border-zinc-700/50">
          <p className="text-zinc-400 text-sm">
            Affichage {page * limit + 1}-{Math.min((page + 1) * limit, meta.total)} sur {meta.total}
          </p>
          <div className="flex gap-2">
            <Button
              variant="outline"
              size="sm"
              className="border-zinc-700 bg-transparent"
              disabled={page === 0}
              onClick={() => setPage((p) => p - 1)}
            >
              <ChevronLeft className="w-4 h-4" />
            </Button>
            <Button
              variant="outline"
              size="sm"
              className="border-zinc-700 bg-transparent"
              disabled={(page + 1) * limit >= meta.total}
              onClick={() => setPage((p) => p + 1)}
            >
              <ChevronRight className="w-4 h-4" />
            </Button>
          </div>
        </div>
      </div>
    </div>
  )
}
