"use client"

import { useState } from "react"
import {
  Search,
  MoreHorizontal,
  CreditCard,
  TrendingUp,
  Users,
  DollarSign,
  Mail,
  Ban,
  RefreshCw,
  Eye,
  Edit,
  ChevronLeft,
  ChevronRight,
  Download,
  Filter,
  Loader2,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent } from "@/components/ui/card"
import useSWR from "swr"

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

export default function AdminSubscriptionsPage() {
  const { data, isLoading, error } = useSWR("/api/admin/subscriptions", fetcher)

  const [searchQuery, setSearchQuery] = useState("")
  const [planFilter, setPlanFilter] = useState("all")
  const [statusFilter, setStatusFilter] = useState("all")
  const [showDetail, setShowDetail] = useState<any | null>(null)
  const [showChangePlan, setShowChangePlan] = useState<any | null>(null)
  const [currentPage, setCurrentPage] = useState(1)

  const subscribers = data?.subscribers || []
  const stats = data?.stats || { totalRevenue: 0, premiumCount: 0, familyCount: 0, studentCount: 0 }
  const plans = data?.plans || []

  const filteredSubscribers = subscribers.filter((sub: any) => {
    const matchesSearch =
      sub.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      sub.email.toLowerCase().includes(searchQuery.toLowerCase())
    const matchesPlan = planFilter === "all" || sub.plan === planFilter
    const matchesStatus = statusFilter === "all" || sub.status === statusFilter
    return matchesSearch && matchesPlan && matchesStatus
  })

  const getStatusBadge = (status: string) => {
    switch (status) {
      case "active":
        return <Badge className="bg-green-500/20 text-green-400 border-0">Actif</Badge>
      case "cancelled":
        return <Badge className="bg-zinc-500/20 text-zinc-400 border-0">Annulé</Badge>
      case "past_due":
        return <Badge className="bg-red-500/20 text-red-400 border-0">Impayé</Badge>
      default:
        return <Badge>{status}</Badge>
    }
  }

  const getPlanBadge = (plan: string) => {
    switch (plan) {
      case "premium":
        return <Badge className="bg-purple-500/20 text-purple-400 border-0">Premium</Badge>
      case "family":
        return <Badge className="bg-blue-500/20 text-blue-400 border-0">Famille</Badge>
      case "student":
        return <Badge className="bg-cyan-500/20 text-cyan-400 border-0">Étudiant</Badge>
      default:
        return <Badge className="bg-zinc-500/20 text-zinc-400 border-0">Gratuit</Badge>
    }
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <Loader2 className="w-8 h-8 animate-spin text-purple-500" />
      </div>
    )
  }

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <p className="text-red-400">Erreur lors du chargement des données</p>
      </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">Abonnements</h1>
          <p className="text-zinc-400 text-sm">Gérez les abonnements des utilisateurs</p>
        </div>
        <Button variant="outline" className="border-zinc-700 text-zinc-300 bg-transparent">
          <Download className="w-4 h-4 mr-2" />
          Exporter
        </Button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-green-500/20 rounded-lg flex items-center justify-center">
                <DollarSign className="w-5 h-5 text-green-400" />
              </div>
              <div>
                <p className="text-zinc-400 text-sm">Revenus mensuels</p>
                <p className="text-xl font-bold text-white">{stats.totalRevenue.toLocaleString()} FCFA</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-purple-500/20 rounded-lg flex items-center justify-center">
                <CreditCard className="w-5 h-5 text-purple-400" />
              </div>
              <div>
                <p className="text-zinc-400 text-sm">Premium</p>
                <p className="text-xl font-bold text-white">{stats.premiumCount}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-blue-500/20 rounded-lg flex items-center justify-center">
                <Users className="w-5 h-5 text-blue-400" />
              </div>
              <div>
                <p className="text-zinc-400 text-sm">Famille</p>
                <p className="text-xl font-bold text-white">{stats.familyCount}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-cyan-500/20 rounded-lg flex items-center justify-center">
                <TrendingUp className="w-5 h-5 text-cyan-400" />
              </div>
              <div>
                <p className="text-zinc-400 text-sm">Étudiant</p>
                <p className="text-xl font-bold text-white">{stats.studentCount}</p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Filters */}
      <div className="flex flex-col gap-4 sm:flex-row">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-400" />
          <Input
            placeholder="Rechercher par nom ou email..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-10 bg-zinc-800/50 border-zinc-700 text-white"
          />
        </div>
        <Select value={planFilter} onValueChange={setPlanFilter}>
          <SelectTrigger className="w-full sm:w-40 bg-zinc-800/50 border-zinc-700 text-white">
            <Filter className="w-4 h-4 mr-2" />
            <SelectValue placeholder="Plan" />
          </SelectTrigger>
          <SelectContent className="bg-zinc-800 border-zinc-700">
            <SelectItem value="all">Tous les plans</SelectItem>
            <SelectItem value="free">Gratuit</SelectItem>
            <SelectItem value="premium">Premium</SelectItem>
            <SelectItem value="family">Famille</SelectItem>
            <SelectItem value="student">Étudiant</SelectItem>
          </SelectContent>
        </Select>
        <Select value={statusFilter} onValueChange={setStatusFilter}>
          <SelectTrigger className="w-full sm: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="active">Actif</SelectItem>
            <SelectItem value="cancelled">Annulé</SelectItem>
            <SelectItem value="past_due">Impayé</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Subscribers 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>
              <tr className="border-b border-zinc-700/50">
                <th className="p-4 text-left text-sm font-medium text-zinc-400">Utilisateur</th>
                <th className="p-4 text-left text-sm font-medium text-zinc-400 hidden md:table-cell">Plan</th>
                <th className="p-4 text-left text-sm font-medium text-zinc-400 hidden lg:table-cell">Statut</th>
                <th className="p-4 text-left text-sm font-medium text-zinc-400 hidden xl:table-cell">
                  Prochain paiement
                </th>
                <th className="p-4 text-left text-sm font-medium text-zinc-400 hidden xl:table-cell">Montant</th>
                <th className="p-4 text-right text-sm font-medium text-zinc-400">Actions</th>
              </tr>
            </thead>
            <tbody>
              {filteredSubscribers.length > 0 ? (
                filteredSubscribers.map((sub: any) => (
                  <tr key={sub.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={sub.avatar || "/placeholder.svg"}
                          alt={sub.name}
                          className="w-10 h-10 rounded-full object-cover"
                        />
                        <div>
                          <p className="font-medium text-white">{sub.name}</p>
                          <p className="text-sm text-zinc-400">{sub.email}</p>
                        </div>
                      </div>
                    </td>
                    <td className="p-4 hidden md:table-cell">{getPlanBadge(sub.plan)}</td>
                    <td className="p-4 hidden lg:table-cell">{getStatusBadge(sub.status)}</td>
                    <td className="p-4 text-zinc-400 text-sm hidden xl:table-cell">{sub.nextBilling || "-"}</td>
                    <td className="p-4 text-white font-medium hidden xl:table-cell">
                      {sub.amount > 0 ? `${sub.amount.toLocaleString()} FCFA/mois` : "-"}
                    </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 onClick={() => setShowDetail(sub)} className="text-zinc-300">
                            <Eye className="w-4 h-4 mr-2" /> Voir les détails
                          </DropdownMenuItem>
                          <DropdownMenuItem onClick={() => setShowChangePlan(sub)} className="text-zinc-300">
                            <Edit className="w-4 h-4 mr-2" /> Changer le plan
                          </DropdownMenuItem>
                          <DropdownMenuItem className="text-zinc-300">
                            <Mail className="w-4 h-4 mr-2" /> Envoyer un email
                          </DropdownMenuItem>
                          {sub.status === "past_due" && (
                            <DropdownMenuItem className="text-zinc-300">
                              <RefreshCw className="w-4 h-4 mr-2" /> Relancer le paiement
                            </DropdownMenuItem>
                          )}
                          <DropdownMenuSeparator className="bg-zinc-700" />
                          <DropdownMenuItem className="text-red-400">
                            <Ban className="w-4 h-4 mr-2" /> Annuler l'abonnement
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={6} className="p-8 text-center text-zinc-400">
                    Aucun abonné trouvé
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        <div className="flex items-center justify-between p-4 border-t border-zinc-700/50">
          <p className="text-sm text-zinc-400">
            Affichage de 1 à {filteredSubscribers.length} sur {filteredSubscribers.length}
          </p>
          <div className="flex items-center gap-2">
            <Button variant="ghost" size="icon" disabled={currentPage === 1} className="text-zinc-400">
              <ChevronLeft className="w-4 h-4" />
            </Button>
            <span className="text-sm text-white px-3 py-1 bg-purple-600 rounded">{currentPage}</span>
            <Button variant="ghost" size="icon" className="text-zinc-400">
              <ChevronRight className="w-4 h-4" />
            </Button>
          </div>
        </div>
      </div>

      {/* Subscription Detail Dialog */}
      <Dialog open={!!showDetail} onOpenChange={() => setShowDetail(null)}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white max-w-lg">
          <DialogHeader>
            <DialogTitle>Détails de l'abonnement</DialogTitle>
          </DialogHeader>
          {showDetail && (
            <div className="space-y-6 py-4">
              <div className="flex items-center gap-4">
                <img
                  src={showDetail.avatar || "/placeholder.svg"}
                  alt={showDetail.name}
                  className="w-16 h-16 rounded-full object-cover"
                />
                <div>
                  <h3 className="text-lg font-bold">{showDetail.name}</h3>
                  <p className="text-zinc-400">{showDetail.email}</p>
                  <div className="flex gap-2 mt-2">
                    {getPlanBadge(showDetail.plan)}
                    {getStatusBadge(showDetail.status)}
                  </div>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="bg-zinc-800/50 rounded-lg p-3">
                  <p className="text-zinc-400 text-sm">Date de début</p>
                  <p className="text-white font-medium">{showDetail.startDate || "N/A"}</p>
                </div>
                <div className="bg-zinc-800/50 rounded-lg p-3">
                  <p className="text-zinc-400 text-sm">Prochain paiement</p>
                  <p className="text-white font-medium">{showDetail.nextBilling || "N/A"}</p>
                </div>
                <div className="bg-zinc-800/50 rounded-lg p-3">
                  <p className="text-zinc-400 text-sm">Montant</p>
                  <p className="text-white font-medium">
                    {showDetail.amount > 0 ? `${showDetail.amount.toLocaleString()} FCFA/mois` : "Gratuit"}
                  </p>
                </div>
                <div className="bg-zinc-800/50 rounded-lg p-3">
                  <p className="text-zinc-400 text-sm">Renouvellement auto</p>
                  <p className="text-white font-medium">{showDetail.autoRenew ? "Oui" : "Non"}</p>
                </div>
              </div>
            </div>
          )}
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowDetail(null)}>
              Fermer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Change Plan Dialog */}
      <Dialog open={!!showChangePlan} onOpenChange={() => setShowChangePlan(null)}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Changer le plan</DialogTitle>
            <DialogDescription className="text-zinc-400">
              Modifier l'abonnement de {showChangePlan?.name}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Nouveau plan</Label>
              <Select defaultValue={showChangePlan?.plan}>
                <SelectTrigger className="bg-zinc-800 border-zinc-700">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent className="bg-zinc-800 border-zinc-700">
                  <SelectItem value="free">Gratuit - 0 FCFA</SelectItem>
                  <SelectItem value="premium">Premium - 6 554 FCFA/mois</SelectItem>
                  <SelectItem value="family">Famille - 9 833 FCFA/mois</SelectItem>
                  <SelectItem value="student">Étudiant - 3 273 FCFA/mois</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowChangePlan(null)}>
              Annuler
            </Button>
            <Button className="bg-purple-600 hover:bg-purple-700" onClick={() => setShowChangePlan(null)}>
              Sauvegarder
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
