"use client"

import { useEffect, useState } from "react"
import { api } from "@/lib/api"
import type { Category } from "@/types"

export default function CategoriesPage() {
  const [categories, setCategories] = useState<Category[]>([])
  const [loading, setLoading] = useState(true)
  const [newName, setNewName] = useState("")
  const [newDescription, setNewDescription] = useState("")

  useEffect(() => {
    api.categories.list().then(setCategories).finally(() => setLoading(false))
  }, [])

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!newName.trim()) return
    const created = await api.categories.create({ name: newName, description: newDescription })
    setCategories([...categories, created])
    setNewName("")
    setNewDescription("")
  }

  const handleDelete = async (id: number) => {
    if (!confirm("¿Eliminar categoría?")) return
    await api.categories.delete(id)
    setCategories(categories.filter((c) => c.id !== id))
  }

  if (loading) return <div className="text-center py-8">Cargando...</div>

  return (
    <div className="max-w-4xl mx-auto">
      <h1 className="text-2xl font-bold mb-6">Categorías</h1>

      <form onSubmit={handleCreate} className="bg-white p-4 rounded-lg shadow mb-6 flex gap-4">
        <input
          value={newName}
          onChange={(e) => setNewName(e.target.value)}
          placeholder="Nombre"
          className="flex-1 px-3 py-2 border rounded"
          required
        />
        <input
          value={newDescription}
          onChange={(e) => setNewDescription(e.target.value)}
          placeholder="Descripción (opcional)"
          className="flex-1 px-3 py-2 border rounded"
        />
        <button type="submit" className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700">
          Agregar
        </button>
      </form>

      <div className="bg-white rounded-lg shadow">
        {categories.map((cat) => (
          <div key={cat.id} className="flex justify-between items-center p-4 border-b last:border-b-0">
            <div>
              <p className="font-medium">{cat.name}</p>
              {cat.description && <p className="text-sm text-gray-500">{cat.description}</p>}
            </div>
            <button onClick={() => handleDelete(cat.id)} className="text-red-600 hover:underline text-sm">
              Eliminar
            </button>
          </div>
        ))}
      </div>
    </div>
  )
}
