'use client'

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

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

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

  const handleCancel = async () => {
    if (!confirm('¿Cancelar esta salida?')) return
    await api.patch(`/salidas/${id}/cancel`)
    const r = await api.get(`/salidas/${id}`)
    setSalida(r.data)
  }

  const downloadPDF = async () => {
    const r = await api.get(`/salidas/${id}/pdf`, { responseType: 'blob' })
    const url = URL.createObjectURL(new Blob([r.data], { type: 'application/pdf' }))
    const a = document.createElement('a'); a.href = url; a.download = `${salida.docNumber}.pdf`; a.click()
    URL.revokeObjectURL(url)
  }

  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 (!salida) return null

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

  return (
    <div className="max-w-4xl space-y-5">
      <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">{salida.docNumber}</h2>
            <p className="text-sm text-gray-500 mt-1">Comprobante de Salida de Inventario</p>
          </div>
          <div className="flex items-center gap-2">
            <span className={`px-3 py-1 rounded-full text-xs font-medium ${salida.status === 'completed' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
              {salida.status === 'completed' ? 'Completado' : 'Cancelado'}
            </span>
            {salida.status === 'completed' && (
              <>
                <button onClick={downloadPDF} className="px-3 py-1 bg-green-50 text-green-700 border border-green-200 rounded-lg text-xs hover:bg-green-100">
                  📄 Descargar PDF
                </button>
                <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(salida.date).toLocaleDateString('es-HN')} />
          <Info label="Proyecto" value={salida.project?.name} />
          <Info label="Bodega" value={salida.warehouse?.name} />
          <Info label="Referencia" value={salida.reference || '—'} />
          <Info label="Destino" value={salida.destination || '—'} />
          <Info label="Beneficiario" value={salida.beneficiary || '—'} />
          <Info label="Registrado por" value={salida.user?.name} />
        </div>
      </div>

      <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">Costo Unit.</th>
              <th className="px-4 py-3 text-right">Costo Total</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100">
            {salida.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">L. {Number(item.unitCost).toLocaleString('es-HN', { minimumFractionDigits: 2 })}</td>
                <td className="px-4 py-3 text-right font-medium text-gray-800">L. {Number(item.totalCost).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">COSTO TOTAL:</td>
              <td className="px-4 py-3 text-right font-bold text-indigo-800 text-base">L. {totalCost.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>
  )
}
