'use client'

import { useEffect, useState } from 'react'
import { useParams, useRouter } from 'next/navigation'
import api from '@/lib/api'

export default function IngresoDetailPage() {
  const { id } = useParams()
  const router = useRouter()
  const [ingreso, setIngreso] = useState<any>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    api.get(`/ingresos/${id}`)
      .then((r) => setIngreso(r.data))
      .catch(() => router.push('/ingresos'))
      .finally(() => setLoading(false))
  }, [id])

  const handleCancel = async () => {
    if (!confirm('¿Cancelar este ingreso? Se revertirá el kardex.')) return
    await api.patch(`/ingresos/${id}/cancel`)
    const r = await api.get(`/ingresos/${id}`)
    setIngreso(r.data)
  }

  if (loading) return <div className="flex items-center justify-center h-40"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600" /></div>
  if (!ingreso) return null

  const total = ingreso.items?.reduce((s: number, i: any) => s + Number(i.total), 0) || 0

  return (
    <div className="max-w-4xl space-y-5">
      {/* Header card */}
      <div className="bg-white rounded-xl shadow-sm border p-5">
        <div className="flex items-start justify-between mb-4">
          <div>
            <h2 className="text-xl font-bold text-gray-800">{ingreso.docNumber}</h2>
            <p className="text-sm text-gray-500 mt-1">Ingreso de Inventario</p>
          </div>
          <div className="flex items-center gap-3">
            <span className={`px-3 py-1 rounded-full text-xs font-medium ${ingreso.status === 'completed' ? 'bg-green-100 text-green-700' : ingreso.status === 'cancelled' ? 'bg-red-100 text-red-700' : 'bg-gray-100 text-gray-600'}`}>
              {ingreso.status === 'completed' ? 'Completado' : ingreso.status === 'cancelled' ? 'Cancelado' : ingreso.status}
            </span>
            {ingreso.status === 'completed' && (
              <button onClick={handleCancel} className="px-3 py-1 bg-red-50 text-red-600 border border-red-200 rounded-lg text-xs hover:bg-red-100">
                Cancelar
              </button>
            )}
          </div>
        </div>
        <div className="grid grid-cols-2 sm:grid-cols-3 gap-4 text-sm">
          <Info label="Fecha" value={new Date(ingreso.date).toLocaleDateString('es-HN')} />
          <Info label="Proyecto" value={ingreso.project?.name} />
          <Info label="Bodega" value={ingreso.warehouse?.name} />
          <Info label="Referencia" value={ingreso.reference || '—'} />
          <Info label="Proveedor" value={ingreso.supplier || '—'} />
          <Info label="Moneda" value={`${ingreso.currency} (TC: ${Number(ingreso.exchangeRate).toFixed(4)})`} />
          <Info label="Registrado por" value={ingreso.user?.name} />
          <Info label="Fecha registro" value={new Date(ingreso.createdAt).toLocaleString('es-HN')} />
        </div>
      </div>

      {/* Items */}
      <div className="bg-white rounded-xl shadow-sm border overflow-hidden">
        <div className="px-5 py-3 border-b bg-gray-50">
          <h3 className="font-semibold text-gray-700 text-sm">Artículos</h3>
        </div>
        <table className="min-w-full text-sm">
          <thead className="bg-gray-50 text-gray-500 uppercase text-xs">
            <tr>
              <th className="px-4 py-3 text-left">SKU</th>
              <th className="px-4 py-3 text-left">Artículo</th>
              <th className="px-4 py-3 text-right">Cantidad</th>
              <th className="px-4 py-3 text-right">Precio Unit.</th>
              <th className="px-4 py-3 text-right">Total</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100">
            {ingreso.items?.map((item: any) => (
              <tr key={item.id} className="hover:bg-gray-50">
                <td className="px-4 py-3 font-mono text-gray-600">{item.item?.sku}</td>
                <td className="px-4 py-3 text-gray-800">{item.item?.name}</td>
                <td className="px-4 py-3 text-right text-gray-700">{Number(item.quantity).toLocaleString('es-HN', { minimumFractionDigits: 2 })} {item.item?.unit}</td>
                <td className="px-4 py-3 text-right text-gray-700">{item.currency} {Number(item.unitPrice).toLocaleString('es-HN', { minimumFractionDigits: 2 })}</td>
                <td className="px-4 py-3 text-right font-medium text-gray-800">{item.currency} {Number(item.total).toLocaleString('es-HN', { minimumFractionDigits: 2 })}</td>
              </tr>
            ))}
          </tbody>
          <tfoot>
            <tr className="bg-indigo-50">
              <td colSpan={4} className="px-4 py-3 text-right font-semibold text-indigo-700">TOTAL:</td>
              <td className="px-4 py-3 text-right font-bold text-indigo-800 text-base">{ingreso.currency} {total.toLocaleString('es-HN', { minimumFractionDigits: 2 })}</td>
            </tr>
          </tfoot>
        </table>
      </div>

      <div className="flex gap-3">
        <button onClick={() => router.back()} className="px-4 py-2 border rounded-lg text-sm hover:bg-gray-50">← Volver</button>
      </div>
    </div>
  )
}

function Info({ label, value }: { label: string; value: any }) {
  return (
    <div>
      <p className="text-xs text-gray-400 uppercase font-medium">{label}</p>
      <p className="text-gray-700 font-medium mt-0.5">{value}</p>
    </div>
  )
}
