"use client"

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

export default function ProductsPage() {
  const [products, setProducts] = useState<Product[]>([])
  const [loading, setLoading] = useState(true)

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

  const handleDelete = async (id: number) => {
    if (!confirm("¿Eliminar producto?")) return
    await api.products.delete(id)
    setProducts(products.filter((p) => p.id !== id))
  }

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

  return (
    <div className="max-w-6xl mx-auto">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold">Productos</h1>
        <a href="/products/new" className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700">
          Nuevo Producto
        </a>
      </div>

      <div className="bg-white rounded-lg shadow overflow-hidden">
        <table className="w-full">
          <thead className="bg-gray-50">
            <tr>
              <th className="text-left p-3">Nombre</th>
              <th className="text-left p-3">SKU</th>
              <th className="text-left p-3">Categoría</th>
              <th className="text-right p-3">Precio</th>
              <th className="text-right p-3">Stock</th>
              <th className="text-right p-3">Stock Mín.</th>
              <th className="text-right p-3">Acciones</th>
            </tr>
          </thead>
          <tbody>
            {products.map((product) => (
              <tr key={product.id} className="border-t hover:bg-gray-50">
                <td className="p-3">{product.name}</td>
                <td className="p-3 text-gray-500">{product.sku}</td>
                <td className="p-3">{product.category?.name}</td>
                <td className="p-3 text-right">${product.price.toFixed(2)}</td>
                <td className={`p-3 text-right ${product.stock <= product.minimumStock ? "text-red-600 font-semibold" : ""}`}>
                  {product.stock}
                </td>
                <td className="p-3 text-right">{product.minimumStock}</td>
                <td className="p-3 text-right space-x-2">
                  <a href={`/products/${product.id}/edit`} className="text-blue-600 hover:underline text-sm">
                    Editar
                  </a>
                  <button onClick={() => handleDelete(product.id)} className="text-red-600 hover:underline text-sm">
                    Eliminar
                  </button>
                  <a href={`/movements?productId=${product.id}`} className="text-gray-600 hover:underline text-sm">
                    Movimientos
                  </a>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}
