"use client"

import { useState } from "react"
import useSWR from "swr"
import { Search, Plus, MoreHorizontal, Edit, Trash2, Eye, GripVertical, 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 {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Switch } from "@/components/ui/switch"
import { useToast } from "@/hooks/use-toast"

const fetcher = (url: string) => {
  const token = typeof window !== "undefined" ? localStorage.getItem("auth_token") : null
  return fetch(url, {
    headers: token ? { Authorization: `Bearer ${token}` } : {},
  }).then((res) => res.json())
}

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

  const [searchQuery, setSearchQuery] = useState("")
  const [showAddDialog, setShowAddDialog] = useState(false)
  const [editingCategory, setEditingCategory] = useState<any | null>(null)
  const [isSaving, setIsSaving] = useState(false)

  const [formData, setFormData] = useState({
    name: "",
    slug: "",
    description: "",
    icon: "",
    color: "#FFB347",
    visible: true,
  })

  const filteredCategories = categories.filter((cat: any) =>
    cat.name?.toLowerCase().includes(searchQuery.toLowerCase()),
  )

  const getAuthHeaders = () => {
    const token = typeof window !== "undefined" ? localStorage.getItem("auth_token") : null
    return {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
    }
  }

  const toggleVisibility = async (id: string, currentVisible: boolean) => {
    try {
      await fetch(`/api/admin/categories/${id}`, {
        method: "PATCH",
        headers: getAuthHeaders(),
        body: JSON.stringify({ is_visible: !currentVisible }),
      })
      mutate()
      toast({ title: "Visibilité modifiée" })
    } catch (e) {
      toast({ title: "Erreur", variant: "destructive" })
    }
  }

  const deleteCategory = async (id: string) => {
    try {
      const token = typeof window !== "undefined" ? localStorage.getItem("auth_token") : null
      await fetch(`/api/admin/categories/${id}`, {
        method: "DELETE",
        headers: token ? { Authorization: `Bearer ${token}` } : {},
      })
      mutate()
      toast({ title: "Catégorie supprimée" })
    } catch (e) {
      toast({ title: "Erreur", variant: "destructive" })
    }
  }

  const handleSave = async () => {
    setIsSaving(true)
    try {
      if (editingCategory) {
        await fetch(`/api/admin/categories/${editingCategory.id}`, {
          method: "PATCH",
          headers: getAuthHeaders(),
          body: JSON.stringify(formData),
        })
        toast({ title: "Catégorie modifiée" })
      } else {
        await fetch("/api/admin/categories", {
          method: "POST",
          headers: getAuthHeaders(),
          body: JSON.stringify(formData),
        })
        toast({ title: "Catégorie créée" })
      }
      mutate()
      setShowAddDialog(false)
      setEditingCategory(null)
      setFormData({ name: "", slug: "", description: "", icon: "", color: "#FFB347", visible: true })
    } catch (e) {
      toast({ title: "Erreur", variant: "destructive" })
    }
    setIsSaving(false)
  }

  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">Catégories</h1>
          <p className="text-zinc-400 text-sm">{categories.length} catégories au total</p>
        </div>
        <Button onClick={() => setShowAddDialog(true)} className="bg-purple-600 hover:bg-purple-700">
          <Plus className="w-4 h-4 mr-2" />
          Ajouter une catégorie
        </Button>
      </div>

      {/* Search */}
      <div className="relative 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 une catégorie..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          className="pl-10 bg-zinc-800/50 border-zinc-700 text-white"
        />
      </div>

      {/* Categories List */}
      {categories.length === 0 ? (
        <div className="text-center py-16 bg-zinc-800/50 rounded-xl border border-zinc-700/50">
          <Plus className="w-16 h-16 mx-auto mb-4 text-zinc-600" />
          <h3 className="text-xl font-medium text-white mb-2">Aucune catégorie</h3>
          <p className="text-zinc-400 mb-6">Commencez par ajouter des catégories</p>
          <Button onClick={() => setShowAddDialog(true)} className="bg-purple-600 hover:bg-purple-700">
            <Plus className="w-4 h-4 mr-2" />
            Ajouter une catégorie
          </Button>
        </div>
      ) : (
        <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 w-12"></th>
                  <th className="p-4 text-left text-sm font-medium text-zinc-400">Catégorie</th>
                  <th className="p-4 text-left text-sm font-medium text-zinc-400 hidden md:table-cell">Description</th>
                  <th className="p-4 text-left text-sm font-medium text-zinc-400">Visible</th>
                  <th className="p-4 text-right text-sm font-medium text-zinc-400">Actions</th>
                </tr>
              </thead>
              <tbody>
                {filteredCategories.map((category: any) => (
                  <tr key={category.id} className="border-b border-zinc-700/30 hover:bg-zinc-700/20 transition-colors">
                    <td className="p-4">
                      <button className="text-zinc-500 hover:text-zinc-300 cursor-grab">
                        <GripVertical className="w-4 h-4" />
                      </button>
                    </td>
                    <td className="p-4">
                      <div className="flex items-center gap-3">
                        <div
                          className="w-10 h-10 rounded-lg flex items-center justify-center text-xl"
                          style={{ backgroundColor: `${category.color || "#FFB347"}20` }}
                        >
                          {category.icon || "📁"}
                        </div>
                        <div>
                          <p className="font-medium text-white">{category.name}</p>
                          <p className="text-sm text-zinc-400">/{category.slug}</p>
                        </div>
                      </div>
                    </td>
                    <td className="p-4 hidden md:table-cell">
                      <p className="text-zinc-400 text-sm truncate max-w-xs">{category.description || "-"}</p>
                    </td>
                    <td className="p-4">
                      <Switch
                        checked={category.is_visible}
                        onCheckedChange={() => toggleVisibility(category.id, category.is_visible)}
                        className="data-[state=checked]:bg-purple-600"
                      />
                    </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 className="text-zinc-300">
                            <Eye className="w-4 h-4 mr-2" /> Voir
                          </DropdownMenuItem>
                          <DropdownMenuItem
                            onClick={() => {
                              setFormData({
                                name: category.name,
                                slug: category.slug,
                                description: category.description || "",
                                icon: category.icon || "",
                                color: category.color || "#FFB347",
                                visible: category.is_visible,
                              })
                              setEditingCategory(category)
                            }}
                            className="text-zinc-300"
                          >
                            <Edit className="w-4 h-4 mr-2" /> Modifier
                          </DropdownMenuItem>
                          <DropdownMenuSeparator className="bg-zinc-700" />
                          <DropdownMenuItem onClick={() => deleteCategory(category.id)} className="text-red-400">
                            <Trash2 className="w-4 h-4 mr-2" /> Supprimer
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Add/Edit Dialog */}
      <Dialog
        open={showAddDialog || !!editingCategory}
        onOpenChange={(open) => {
          setShowAddDialog(open)
          if (!open) {
            setEditingCategory(null)
            setFormData({ name: "", slug: "", description: "", icon: "", color: "#FFB347", visible: true })
          }
        }}
      >
        <DialogContent className="bg-zinc-900 border-zinc-700 text-white max-w-lg">
          <DialogHeader>
            <DialogTitle>{editingCategory ? "Modifier la catégorie" : "Ajouter une catégorie"}</DialogTitle>
            <DialogDescription className="text-zinc-400">
              {editingCategory ? "Modifiez les informations de la catégorie" : "Créer une nouvelle catégorie"}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Nom</Label>
                <Input
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  className="bg-zinc-800 border-zinc-700"
                  placeholder="Humeurs"
                />
              </div>
              <div className="space-y-2">
                <Label>Slug</Label>
                <Input
                  value={formData.slug}
                  onChange={(e) => setFormData({ ...formData, slug: e.target.value })}
                  className="bg-zinc-800 border-zinc-700"
                  placeholder="moods"
                />
              </div>
            </div>
            <div className="space-y-2">
              <Label>Description</Label>
              <Textarea
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                className="bg-zinc-800 border-zinc-700"
                placeholder="Description de la catégorie..."
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>Icône</Label>
                <Input
                  value={formData.icon}
                  onChange={(e) => setFormData({ ...formData, icon: e.target.value })}
                  className="bg-zinc-800 border-zinc-700"
                  placeholder="😊"
                />
              </div>
              <div className="space-y-2">
                <Label>Couleur</Label>
                <div className="flex gap-2">
                  <Input
                    type="color"
                    value={formData.color}
                    onChange={(e) => setFormData({ ...formData, color: e.target.value })}
                    className="w-12 h-10 p-1 bg-zinc-800 border-zinc-700"
                  />
                  <Input
                    value={formData.color}
                    onChange={(e) => setFormData({ ...formData, color: e.target.value })}
                    className="bg-zinc-800 border-zinc-700 font-mono"
                  />
                </div>
              </div>
            </div>
            <div className="flex items-center justify-between">
              <Label>Visible sur l'app</Label>
              <Switch
                checked={formData.visible}
                onCheckedChange={(checked) => setFormData({ ...formData, visible: checked })}
                className="data-[state=checked]:bg-purple-600"
              />
            </div>
          </div>
          <DialogFooter>
            <Button
              variant="ghost"
              onClick={() => {
                setShowAddDialog(false)
                setEditingCategory(null)
              }}
            >
              Annuler
            </Button>
            <Button className="bg-purple-600 hover:bg-purple-700" onClick={handleSave} disabled={isSaving}>
              {isSaving ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : null}
              {editingCategory ? "Sauvegarder" : "Créer"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
