"use client"

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

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

export default function AdminNotificationsPage() {
  const { toast } = useToast()
  const { data, error, isLoading, mutate } = useSWR("/api/admin/notifications", fetcher)
  const notifications = data?.notifications || []
  const stats = data?.stats || { total: 0, deliveryRate: 0, openRate: 0, scheduled: 0 }

  const [showSendDialog, setShowSendDialog] = useState(false)
  const [isSending, setIsSending] = useState(false)
  const [formData, setFormData] = useState({
    title: "",
    message: "",
    type: "info",
    target: "all",
    scheduledFor: "",
  })

  const getTypeBadge = (type: string) => {
    const types: Record<string, { color: string; label: string }> = {
      info: { color: "bg-blue-500/20 text-blue-400", label: "Info" },
      success: { color: "bg-green-500/20 text-green-400", label: "Succès" },
      warning: { color: "bg-yellow-500/20 text-yellow-400", label: "Attention" },
      error: { color: "bg-red-500/20 text-red-400", label: "Erreur" },
      promo: { color: "bg-purple-500/20 text-purple-400", label: "Promotion" },
    }
    const t = types[type] || { color: "bg-zinc-500/20 text-zinc-400", label: type }
    return <Badge className={`${t.color} border-0`}>{t.label}</Badge>
  }

  const getStatusBadge = (status: string) => {
    switch (status) {
      case "sent":
        return <Badge className="bg-green-500/20 text-green-400 border-0">Envoyé</Badge>
      case "scheduled":
        return <Badge className="bg-blue-500/20 text-blue-400 border-0">Programmé</Badge>
      case "draft":
        return <Badge className="bg-zinc-500/20 text-zinc-400 border-0">Brouillon</Badge>
      default:
        return <Badge>{status}</Badge>
    }
  }

  const formatNumber = (num: number) => {
    if (num >= 1000) return `${(num / 1000).toFixed(1)}K`
    return num.toString()
  }

  const handleSend = async () => {
    setIsSending(true)
    try {
      const res = await fetch("/api/admin/notifications", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
      })
      if (res.ok) {
        toast({ title: formData.scheduledFor ? "Notification programmée" : "Notification envoyée" })
        mutate()
        setShowSendDialog(false)
        setFormData({ title: "", message: "", type: "info", target: "all", scheduledFor: "" })
      }
    } catch (e) {
      toast({ title: "Erreur", variant: "destructive" })
    }
    setIsSending(false)
  }

  const handleDelete = async (id: string) => {
    try {
      await fetch(`/api/admin/notifications/${id}`, { method: "DELETE" })
      mutate()
      toast({ title: "Notification supprimée" })
    } 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">Notifications</h1>
          <p className="text-zinc-400 text-sm">Envoyez des notifications push aux utilisateurs</p>
        </div>
        <Button onClick={() => setShowSendDialog(true)} className="bg-purple-600 hover:bg-purple-700">
          <Send className="w-4 h-4 mr-2" />
          Envoyer une notification
        </Button>
      </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-purple-500/20">
              <Bell className="w-5 h-5 text-purple-400" />
            </div>
            <div>
              <p className="text-2xl font-bold text-white">{stats.total}</p>
              <p className="text-zinc-400 text-sm">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-green-500/20">
              <CheckCircle className="w-5 h-5 text-green-400" />
            </div>
            <div>
              <p className="text-2xl font-bold text-white">{stats.deliveryRate}%</p>
              <p className="text-zinc-400 text-sm">Taux livraison</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">
              <Users className="w-5 h-5 text-blue-400" />
            </div>
            <div>
              <p className="text-2xl font-bold text-white">{stats.openRate}%</p>
              <p className="text-zinc-400 text-sm">Taux ouverture</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-pink-500/20">
              <Clock className="w-5 h-5 text-pink-400" />
            </div>
            <div>
              <p className="text-2xl font-bold text-white">{stats.scheduled}</p>
              <p className="text-zinc-400 text-sm">Programmées</p>
            </div>
          </div>
        </div>
      </div>

      <Tabs defaultValue="history" className="space-y-4">
        <TabsList className="bg-zinc-800/50 border border-zinc-700/50">
          <TabsTrigger value="history" className="data-[state=active]:bg-purple-600">
            Historique
          </TabsTrigger>
          <TabsTrigger value="scheduled" className="data-[state=active]:bg-purple-600">
            Programmées
          </TabsTrigger>
        </TabsList>

        <TabsContent value="history" className="space-y-4">
          {notifications.length === 0 ? (
            <div className="text-center py-16 bg-zinc-800/50 rounded-xl border border-zinc-700/50">
              <Bell className="w-16 h-16 mx-auto mb-4 text-zinc-600" />
              <h3 className="text-xl font-medium text-white mb-2">Aucune notification</h3>
              <p className="text-zinc-400 mb-6">Envoyez votre première notification</p>
              <Button onClick={() => setShowSendDialog(true)} className="bg-purple-600 hover:bg-purple-700">
                <Send className="w-4 h-4 mr-2" />
                Envoyer une notification
              </Button>
            </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">Notification</th>
                    <th className="p-4 text-left text-sm font-medium text-zinc-400 hidden md:table-cell">Type</th>
                    <th className="p-4 text-left text-sm font-medium text-zinc-400 hidden lg:table-cell">Cible</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>
                  {notifications.map((notif: any) => (
                    <tr key={notif.id} className="border-b border-zinc-700/30 hover:bg-zinc-700/20 transition-colors">
                      <td className="p-4">
                        <div>
                          <p className="font-medium text-white">{notif.title}</p>
                          <p className="text-sm text-zinc-400 truncate max-w-xs">{notif.message}</p>
                          <p className="text-xs text-zinc-500 mt-1">
                            {notif.sent_at ? new Date(notif.sent_at).toLocaleString("fr-FR") : "-"}
                          </p>
                        </div>
                      </td>
                      <td className="p-4 hidden md:table-cell">{getTypeBadge(notif.type)}</td>
                      <td className="p-4 text-zinc-400 hidden lg:table-cell">{notif.target || "Tous"}</td>
                      <td className="p-4">{getStatusBadge(notif.status || "sent")}</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={() => handleDelete(notif.id)} className="text-red-400">
                              <Trash2 className="w-4 h-4 mr-2" /> Supprimer
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </TabsContent>

        <TabsContent value="scheduled" className="space-y-4">
          <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">Notification</th>
                  <th className="p-4 text-left text-sm font-medium text-zinc-400">Type</th>
                  <th className="p-4 text-left text-sm font-medium text-zinc-400">Programmée pour</th>
                  <th className="p-4 text-right text-sm font-medium text-zinc-400">Actions</th>
                </tr>
              </thead>
              <tbody>
                {notifications
                  .filter((n: any) => n.status === "scheduled")
                  .map((notif: any) => (
                    <tr key={notif.id} className="border-b border-zinc-700/30 hover:bg-zinc-700/20 transition-colors">
                      <td className="p-4">
                        <div>
                          <p className="font-medium text-white">{notif.title}</p>
                          <p className="text-sm text-zinc-400">{notif.message}</p>
                        </div>
                      </td>
                      <td className="p-4">{getTypeBadge(notif.type)}</td>
                      <td className="p-4 text-white">
                        {notif.scheduled_for ? new Date(notif.scheduled_for).toLocaleString("fr-FR") : "-"}
                      </td>
                      <td className="p-4 text-right">
                        <div className="flex justify-end gap-2">
                          <Button size="sm" variant="ghost" className="text-zinc-400">
                            Modifier
                          </Button>
                          <Button
                            size="sm"
                            variant="ghost"
                            className="text-red-400"
                            onClick={() => handleDelete(notif.id)}
                          >
                            <XCircle className="w-4 h-4" />
                          </Button>
                        </div>
                      </td>
                    </tr>
                  ))}
              </tbody>
            </table>
          </div>
        </TabsContent>
      </Tabs>

      {/* Send Notification Dialog */}
      <Dialog open={showSendDialog} onOpenChange={setShowSendDialog}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white max-w-lg">
          <DialogHeader>
            <DialogTitle>Envoyer une notification</DialogTitle>
            <DialogDescription className="text-zinc-400">
              Envoyez une notification push aux utilisateurs
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Titre</Label>
              <Input
                value={formData.title}
                onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                className="bg-zinc-800 border-zinc-700"
                placeholder="Titre de la notification"
              />
            </div>
            <div className="space-y-2">
              <Label>Message</Label>
              <Textarea
                value={formData.message}
                onChange={(e) => setFormData({ ...formData, message: e.target.value })}
                className="bg-zinc-800 border-zinc-700 min-h-24"
                placeholder="Votre message..."
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Type</Label>
                <Select value={formData.type} onValueChange={(v) => setFormData({ ...formData, type: v })}>
                  <SelectTrigger className="bg-zinc-800 border-zinc-700">
                    <SelectValue placeholder="Sélectionner" />
                  </SelectTrigger>
                  <SelectContent className="bg-zinc-800 border-zinc-700">
                    <SelectItem value="info">Info</SelectItem>
                    <SelectItem value="success">Succès</SelectItem>
                    <SelectItem value="warning">Attention</SelectItem>
                    <SelectItem value="error">Erreur</SelectItem>
                    <SelectItem value="promo">Promotion</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Cible</Label>
                <Select value={formData.target} onValueChange={(v) => setFormData({ ...formData, target: v })}>
                  <SelectTrigger className="bg-zinc-800 border-zinc-700">
                    <SelectValue placeholder="Sélectionner" />
                  </SelectTrigger>
                  <SelectContent className="bg-zinc-800 border-zinc-700">
                    <SelectItem value="all">Tous les utilisateurs</SelectItem>
                    <SelectItem value="free_users">Utilisateurs gratuits</SelectItem>
                    <SelectItem value="premium">Premium</SelectItem>
                    <SelectItem value="artists">Artistes</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="space-y-2">
              <Label>Programmer (optionnel)</Label>
              <Input
                type="datetime-local"
                value={formData.scheduledFor}
                onChange={(e) => setFormData({ ...formData, scheduledFor: e.target.value })}
                className="bg-zinc-800 border-zinc-700"
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowSendDialog(false)}>
              Annuler
            </Button>
            <Button className="bg-purple-600 hover:bg-purple-700" onClick={handleSend} disabled={isSending}>
              {isSending ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : <Send className="w-4 h-4 mr-2" />}
              Envoyer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
