"use client"

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

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

export default function AdminPromotionsPage() {
  const { toast } = useToast()
  const { data, error, isLoading, mutate } = useSWR("/api/admin/promotions", fetcher)
  const promotions = data?.promotions || []
  const banners = data?.banners || []

  const [searchQuery, setSearchQuery] = useState("")
  const [showAddPromo, setShowAddPromo] = useState(false)
  const [showAddBanner, setShowAddBanner] = useState(false)
  const [isSaving, setIsSaving] = useState(false)

  const [promoForm, setPromoForm] = useState({
    title: "",
    description: "",
    type: "discount",
    target: "all",
    startDate: "",
    endDate: "",
    discount: 0,
  })

  const [bannerForm, setBannerForm] = useState({
    title: "",
    placement: "home_hero",
  })

  const filteredPromotions = promotions.filter((promo: any) =>
    promo.title?.toLowerCase().includes(searchQuery.toLowerCase()),
  )

  const getStatusBadge = (status: string) => {
    switch (status) {
      case "active":
        return <Badge className="bg-green-500/20 text-green-400 border-0">Actif</Badge>
      case "scheduled":
        return <Badge className="bg-blue-500/20 text-blue-400 border-0">Programmé</Badge>
      case "ended":
        return <Badge className="bg-zinc-500/20 text-zinc-400 border-0">Terminé</Badge>
      case "inactive":
        return <Badge className="bg-zinc-500/20 text-zinc-400 border-0">Inactif</Badge>
      default:
        return <Badge>{status}</Badge>
    }
  }

  const getTypeBadge = (type: string) => {
    switch (type) {
      case "discount":
        return <Badge className="bg-purple-500/20 text-purple-400 border-0">Réduction</Badge>
      case "trial":
        return <Badge className="bg-cyan-500/20 text-cyan-400 border-0">Essai</Badge>
      case "content":
        return <Badge className="bg-pink-500/20 text-pink-400 border-0">Contenu</Badge>
      default:
        return <Badge>{type}</Badge>
    }
  }

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

  const handleCreatePromo = async () => {
    setIsSaving(true)
    try {
      const res = await fetch("/api/admin/promotions", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...promoForm, entityType: "promotion" }),
      })
      if (res.ok) {
        toast({ title: "Promotion créée" })
        mutate()
        setShowAddPromo(false)
        setPromoForm({
          title: "",
          description: "",
          type: "discount",
          target: "all",
          startDate: "",
          endDate: "",
          discount: 0,
        })
      }
    } catch (e) {
      toast({ title: "Erreur", variant: "destructive" })
    }
    setIsSaving(false)
  }

  const handleCreateBanner = async () => {
    setIsSaving(true)
    try {
      const res = await fetch("/api/admin/promotions", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...bannerForm, entityType: "banner" }),
      })
      if (res.ok) {
        toast({ title: "Bannière créée" })
        mutate()
        setShowAddBanner(false)
        setBannerForm({ title: "", placement: "home_hero" })
      }
    } catch (e) {
      toast({ title: "Erreur", variant: "destructive" })
    }
    setIsSaving(false)
  }

  const handleDelete = async (id: string, type: string) => {
    try {
      await fetch(`/api/admin/promotions/${id}?type=${type}`, { method: "DELETE" })
      mutate()
      toast({ title: "Élément supprimé" })
    } 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">Promotions</h1>
          <p className="text-zinc-400 text-sm">Gérez vos campagnes et bannières</p>
        </div>
      </div>

      <Tabs defaultValue="promotions" className="space-y-4">
        <TabsList className="bg-zinc-800/50 border border-zinc-700/50">
          <TabsTrigger value="promotions" className="data-[state=active]:bg-purple-600">
            Promotions
          </TabsTrigger>
          <TabsTrigger value="banners" className="data-[state=active]:bg-purple-600">
            Bannières
          </TabsTrigger>
        </TabsList>

        <TabsContent value="promotions" className="space-y-4">
          <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
            <div className="relative flex-1 max-w-md">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-400" />
              <Input
                placeholder="Rechercher..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-10 bg-zinc-800/50 border-zinc-700 text-white"
              />
            </div>
            <Button onClick={() => setShowAddPromo(true)} className="bg-purple-600 hover:bg-purple-700">
              <Plus className="w-4 h-4 mr-2" />
              Nouvelle promotion
            </Button>
          </div>

          {promotions.length === 0 ? (
            <div className="text-center py-16 bg-zinc-800/50 rounded-xl border border-zinc-700/50">
              <Target className="w-16 h-16 mx-auto mb-4 text-zinc-600" />
              <h3 className="text-xl font-medium text-white mb-2">Aucune promotion</h3>
              <p className="text-zinc-400 mb-6">Créez votre première campagne promotionnelle</p>
              <Button onClick={() => setShowAddPromo(true)} className="bg-purple-600 hover:bg-purple-700">
                <Plus className="w-4 h-4 mr-2" />
                Nouvelle promotion
              </Button>
            </div>
          ) : (
            <div className="grid gap-4 md:grid-cols-2">
              {filteredPromotions.map((promo: any) => (
                <div
                  key={promo.id}
                  className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 p-4 hover:bg-zinc-800/50 transition-colors"
                >
                  <div className="flex items-start justify-between mb-4">
                    <div className="flex items-start gap-3">
                      <div className="w-16 h-16 bg-gradient-to-br from-purple-500 to-pink-500 rounded-lg" />
                      <div>
                        <h3 className="font-semibold text-white">{promo.title}</h3>
                        <p className="text-zinc-400 text-sm">{promo.description}</p>
                        <div className="flex gap-2 mt-2">
                          {getTypeBadge(promo.type)}
                          {getStatusBadge(promo.status)}
                        </div>
                      </div>
                    </div>
                    <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 className="text-zinc-300">
                          <Eye className="w-4 h-4 mr-2" /> Voir
                        </DropdownMenuItem>
                        <DropdownMenuItem className="text-zinc-300">
                          <Edit className="w-4 h-4 mr-2" /> Modifier
                        </DropdownMenuItem>
                        <DropdownMenuSeparator className="bg-zinc-700" />
                        <DropdownMenuItem onClick={() => handleDelete(promo.id, "promotion")} className="text-red-400">
                          <Trash2 className="w-4 h-4 mr-2" /> Supprimer
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </div>
                  <div className="grid grid-cols-3 gap-4 pt-4 border-t border-zinc-700/50">
                    <div className="flex items-center gap-2">
                      <Calendar className="w-4 h-4 text-zinc-400" />
                      <div>
                        <p className="text-xs text-zinc-500">Période</p>
                        <p className="text-sm text-white">
                          {promo.start_date ? new Date(promo.start_date).toLocaleDateString("fr-FR") : "-"} -{" "}
                          {promo.end_date ? new Date(promo.end_date).toLocaleDateString("fr-FR") : "-"}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <Eye className="w-4 h-4 text-zinc-400" />
                      <div>
                        <p className="text-xs text-zinc-500">Vues</p>
                        <p className="text-sm text-white">{formatNumber(promo.views || 0)}</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <Target className="w-4 h-4 text-zinc-400" />
                      <div>
                        <p className="text-xs text-zinc-500">Conversions</p>
                        <p className="text-sm text-white">{formatNumber(promo.conversions || 0)}</p>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </TabsContent>

        <TabsContent value="banners" className="space-y-4">
          <div className="flex justify-end">
            <Button onClick={() => setShowAddBanner(true)} className="bg-purple-600 hover:bg-purple-700">
              <Plus className="w-4 h-4 mr-2" />
              Nouvelle bannière
            </Button>
          </div>

          {banners.length === 0 ? (
            <div className="text-center py-16 bg-zinc-800/50 rounded-xl border border-zinc-700/50">
              <Zap className="w-16 h-16 mx-auto mb-4 text-zinc-600" />
              <h3 className="text-xl font-medium text-white mb-2">Aucune bannière</h3>
              <p className="text-zinc-400 mb-6">Créez votre première bannière publicitaire</p>
              <Button onClick={() => setShowAddBanner(true)} className="bg-purple-600 hover:bg-purple-700">
                <Plus className="w-4 h-4 mr-2" />
                Nouvelle bannière
              </Button>
            </div>
          ) : (
            <div className="grid gap-4 md:grid-cols-3">
              {banners.map((banner: any) => (
                <div
                  key={banner.id}
                  className="bg-zinc-800/30 rounded-xl border border-zinc-700/50 overflow-hidden hover:bg-zinc-800/50 transition-colors"
                >
                  <div className="aspect-video bg-gradient-to-br from-purple-500/30 to-pink-500/30" />
                  <div className="p-4">
                    <div className="flex items-start justify-between">
                      <div>
                        <h3 className="font-semibold text-white">{banner.title}</h3>
                        <p className="text-zinc-400 text-sm">{banner.placement}</p>
                      </div>
                      {getStatusBadge(banner.status || "active")}
                    </div>
                    <div className="flex items-center gap-2 mt-3 text-zinc-400 text-sm">
                      <Zap className="w-4 h-4" />
                      {formatNumber(banner.clicks || 0)} clics
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </TabsContent>
      </Tabs>

      {/* Add Promotion Dialog */}
      <Dialog open={showAddPromo} onOpenChange={setShowAddPromo}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white max-w-lg">
          <DialogHeader>
            <DialogTitle>Nouvelle promotion</DialogTitle>
            <DialogDescription className="text-zinc-400">Créer une nouvelle campagne promotionnelle</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Titre</Label>
              <Input
                value={promoForm.title}
                onChange={(e) => setPromoForm({ ...promoForm, title: e.target.value })}
                className="bg-zinc-800 border-zinc-700"
                placeholder="50% sur Premium"
              />
            </div>
            <div className="space-y-2">
              <Label>Description</Label>
              <Textarea
                value={promoForm.description}
                onChange={(e) => setPromoForm({ ...promoForm, description: e.target.value })}
                className="bg-zinc-800 border-zinc-700"
                placeholder="Description de l'offre..."
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Type</Label>
                <Select value={promoForm.type} onValueChange={(v) => setPromoForm({ ...promoForm, 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="discount">Réduction</SelectItem>
                    <SelectItem value="trial">Essai gratuit</SelectItem>
                    <SelectItem value="content">Contenu</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Cible</Label>
                <Select value={promoForm.target} onValueChange={(v) => setPromoForm({ ...promoForm, 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</SelectItem>
                    <SelectItem value="free_users">Utilisateurs gratuits</SelectItem>
                    <SelectItem value="new_users">Nouveaux utilisateurs</SelectItem>
                    <SelectItem value="premium">Premium</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Date de début</Label>
                <Input
                  type="date"
                  value={promoForm.startDate}
                  onChange={(e) => setPromoForm({ ...promoForm, startDate: e.target.value })}
                  className="bg-zinc-800 border-zinc-700"
                />
              </div>
              <div className="space-y-2">
                <Label>Date de fin</Label>
                <Input
                  type="date"
                  value={promoForm.endDate}
                  onChange={(e) => setPromoForm({ ...promoForm, endDate: e.target.value })}
                  className="bg-zinc-800 border-zinc-700"
                />
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowAddPromo(false)}>
              Annuler
            </Button>
            <Button className="bg-purple-600 hover:bg-purple-700" onClick={handleCreatePromo} disabled={isSaving}>
              {isSaving ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : null}
              Créer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Add Banner Dialog */}
      <Dialog open={showAddBanner} onOpenChange={setShowAddBanner}>
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white">
          <DialogHeader>
            <DialogTitle>Nouvelle bannière</DialogTitle>
            <DialogDescription className="text-zinc-400">Ajouter une nouvelle bannière publicitaire</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Titre</Label>
              <Input
                value={bannerForm.title}
                onChange={(e) => setBannerForm({ ...bannerForm, title: e.target.value })}
                className="bg-zinc-800 border-zinc-700"
                placeholder="Titre de la bannière"
              />
            </div>
            <div className="space-y-2">
              <Label>Emplacement</Label>
              <Select
                value={bannerForm.placement}
                onValueChange={(v) => setBannerForm({ ...bannerForm, placement: v })}
              >
                <SelectTrigger className="bg-zinc-800 border-zinc-700">
                  <SelectValue placeholder="Sélectionner" />
                </SelectTrigger>
                <SelectContent className="bg-zinc-800 border-zinc-700">
                  <SelectItem value="home_hero">Accueil - Hero</SelectItem>
                  <SelectItem value="home_section">Accueil - Section</SelectItem>
                  <SelectItem value="search">Recherche</SelectItem>
                  <SelectItem value="library">Bibliothèque</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setShowAddBanner(false)}>
              Annuler
            </Button>
            <Button className="bg-purple-600 hover:bg-purple-700" onClick={handleCreateBanner} disabled={isSaving}>
              {isSaving ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : null}
              Créer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
