"use client"

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

export default function MovementsPage() {
  const [movements, setMovements] = useState<InventoryMovement[]>([])
  const [products, setProducts] = useState<Product[]>([])
  const [loading, setLoading] = useState(true)
  const [productId, setProductId] = useState("")
  const [type, setType] = useState<"Entry" | "Exit">("Entry")
  const [quantity, setQuantity] = useState("")
  const [notes, setNotes] = useState("")

  useEffect(() => {
    Promise.all([api.movements.list(), api.products.list()])
      .then(([m, p]) => {
        setMovements(m)
        setProducts(p)
      })
      .finally(() => setLoading(false))
  }, [])

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!productId || !quantity) return
    const movement = await api.movements.create({
      productId: Number(productId),
      type,
      quantity: Number(quantity),
      notes,
    })
    setMovements([movement, ...movements])
    setQuantity("")
    setNotes("")
  }

  const formatDate = (date: string) => new Date(date).toLocaleString("es-ES")

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

  return (
    <div className="max-w-6xl mx-auto">
      <h1 className="text-2xl font-bold mb-6">Movimientos de Inventario</h1>

      <form onSubmit={handleCreate} className="bg-white p-4 rounded-lg shadow mb-6 flex flex-wrap gap-4">
        <select
          value={productId}
          onChange={(e) => setProductId(e.target.value)}
          className="px-3 py-2 border rounded"
          required
        >
          <option value="">Seleccionar producto</option>
          {products.map((p) => (
            <option key={p.id} value={p.id}>
              {p.name}
            </option>
          ))}
        </select>
        <select
          value={type}
          onChange={(e) => setType(e.target.value as "Entry" | "Exit")}
          className="px-3 py-2 border rounded"
        >
          <option value="Entry">Entrada</option>
          <option value="Exit">Salida</option>
        </select>
        <input
          type="number"
          value={quantity}
          onChange={(e) => setQuantity(e.target.value)}
          placeholder="Cantidad"
          className="px-3 py-2 border rounded w-24"
          required
          min="1"
        />
        <input
          value={notes}
          onChange={(e) => setNotes(e.target.value)}
          placeholder="Notas (opcional)"
          className="px-3 py-2 border rounded flex-1"
        />
        <button type="submit" className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700">
          Registrar
        </button>
      </form>

      <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">Fecha</th>
              <th className="text-left p-3">Producto</th>
              <th className="text-left p-3">Tipo</th>
              <th className="text-right p-3">Cantidad</th>
              <th className="text-left p-3">Notas</th>
            </tr>
          </thead>
          <tbody>
            {movements.map((m) => (
              <tr key={m.id} className="border-t hover:bg-gray-50">
                <td className="p-3 text-sm text-gray-500">{formatDate(m.createdAt)}</td>
                <td className="p-3">{m.product?.name}</td>
                <td className="p-3">
                  <span
                    className={`px-2 py-1 rounded text-xs font-medium ${
                      m.type === "Entry" ? "bg-green-100 text-green-700" : "bg-red-100 text-red-700"
                    }`}
                  >
                    {m.type === "Entry" ? "Entrada" : "Salida"}
                  </span>
                </td>
                <td className="p-3 text-right">{m.quantity}</td>
                <td className="p-3 text-gray-500 text-sm">{m.notes}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}
