'use client'

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

interface LineItem { itemId: string; quantity: string }

export default function NuevaSalidaPage() {
  const router = useRouter()
  const [proyectos, setProyectos] = useState<any[]>([])
  const [bodegas, setBodegas] = useState<any[]>([])
  const [articulos, setArticulos] = useState<any[]>([])
  const [articulosConStock, setArticulosConStock] = useState<any[]>([])
  const [stockData, setStockData] = useState<Map<number, number>>(new Map())
  const [selectedProject, setSelectedProject] = useState('')
  const [form, setForm] = useState({ date: new Date().toISOString().split('T')[0], warehouseId: '', reference: '', destination: '', beneficiary: '' })
  const [lines, setLines] = useState<LineItem[]>([{ itemId: '', quantity: '' }])
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState(false)
  const [scanInput, setScanInput] = useState('')
  const [scanning, setScanning] = useState(false)

  useEffect(() => {
    api.get('/projects', { params: { activeOnly: true } })
      .then((r) => setProyectos(Array.isArray(r.data) ? r.data : r.data.data ?? []))
      .catch(console.error)
    api.get('/items', { params: { activeOnly: true } })
      .then((r) => setArticulos(Array.isArray(r.data) ? r.data : r.data.data ?? []))
      .catch(console.error)
  }, [])

  useEffect(() => {
    if (selectedProject) {
      api.get('/warehouses', { params: { projectId: selectedProject, activeOnly: true } })
        .then((r) => setBodegas(Array.isArray(r.data) ? r.data : r.data.data ?? []))
        .catch(console.error)
    } else { 
      setBodegas([]) 
    }
    // Limpiar bodega y stock cuando cambia el proyecto
    setForm((f) => ({ ...f, warehouseId: '' }))
    setArticulosConStock([])
    setStockData(new Map())
    setLines([{ itemId: '', quantity: '' }])
  }, [selectedProject])

  useEffect(() => {
    if (form.warehouseId) {
      // Obtener stock on hand específicamente para la bodega seleccionada
      api.get('/reports/stock-on-hand', { params: { warehouseId: form.warehouseId } })
        .then((r) => {
          const stock = new Map<number, number>()
          const itemsWithStock: any[] = []
          
          // Crear mapa de stock por itemId (solo para esta bodega específica)
          const stockEntries = Array.isArray(r.data) ? r.data : []
          const selectedWarehouseId = Number(form.warehouseId)
          
          stockEntries.forEach((entry: any) => {
            // Verificar que el stock pertenece a la bodega seleccionada
            const entryWarehouseId = entry.warehouseId || entry.warehouse?.id
            if (entryWarehouseId !== selectedWarehouseId) {
              return // Saltar entradas de otras bodegas
            }
            
            const qty = typeof entry.quantity === 'object' && entry.quantity?.toNumber 
              ? entry.quantity.toNumber() 
              : parseFloat(entry.quantity) || 0
            
            // Solo incluir artículos con stock > 0 en esta bodega específica
            if (qty > 0) {
              stock.set(entry.itemId, qty)
              // Buscar el artículo completo en la lista de artículos
              const item = articulos.find((a) => a.id === entry.itemId)
              if (item) {
                itemsWithStock.push({ ...item, stock: qty })
              }
            }
          })
          
          setStockData(stock)
          setArticulosConStock(itemsWithStock)
          
          // Limpiar líneas que tengan artículos sin stock en esta bodega
          setLines((prevLines) => 
            prevLines.map((line) => {
              if (line.itemId && !stock.has(Number(line.itemId))) {
                return { itemId: '', quantity: '' }
              }
              return line
            })
          )
        })
        .catch((err) => {
          console.error('Error loading stock:', err)
          setArticulosConStock([])
          setStockData(new Map())
        })
    } else {
      setArticulosConStock([])
      setStockData(new Map())
      // Limpiar las líneas cuando no hay bodega seleccionada
      setLines([{ itemId: '', quantity: '' }])
    }
  }, [form.warehouseId, articulos])

  const addLine = () => setLines([...lines, { itemId: '', quantity: '' }])
  const removeLine = (i: number) => setLines(lines.filter((_, idx) => idx !== i))
  const updateLine = (i: number, f: keyof LineItem, v: string) => { const u = [...lines]; u[i] = { ...u[i], [f]: v }; setLines(u) }

  const handleScan = async (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter' && scanInput.trim()) {
      e.preventDefault()
      setScanning(true)
      const sku = scanInput.trim().toUpperCase()
      
      // Buscar artículo por SKU (solo en artículos con stock)
      const item = articulosConStock.find((a) => a.sku.toUpperCase() === sku)
      
      if (item) {
        // Buscar si ya existe en las líneas
        const existingIndex = lines.findIndex((l) => l.itemId === item.id.toString())
        
        if (existingIndex >= 0) {
          // Si existe, incrementar cantidad en 1
          const currentQty = parseFloat(lines[existingIndex].quantity) || 0
          updateLine(existingIndex, 'quantity', (currentQty + 1).toString())
        } else {
          // Si no existe, agregar nueva línea
          const emptyIndex = lines.findIndex((l) => !l.itemId)
          if (emptyIndex >= 0) {
            updateLine(emptyIndex, 'itemId', item.id.toString())
            updateLine(emptyIndex, 'quantity', '1')
          } else {
            setLines([...lines, { itemId: item.id.toString(), quantity: '1' }])
          }
        }
        
        // Feedback visual
        const scanInputEl = e.currentTarget
        scanInputEl.style.backgroundColor = '#d1fae5'
        setTimeout(() => {
          scanInputEl.style.backgroundColor = ''
        }, 300)
      } else {
        setError(`Artículo con SKU "${sku}" no encontrado`)
        setTimeout(() => setError(''), 3000)
      }
      
      setScanInput('')
      setScanning(false)
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!form.warehouseId) { setError('Seleccione una bodega'); return }
    if (lines.some((l) => !l.itemId || !l.quantity)) { setError('Complete todos los artículos'); return }
    
    // Validar que las cantidades no excedan el stock disponible
    for (const line of lines) {
      const itemId = Number(line.itemId)
      const quantity = parseFloat(line.quantity)
      const availableStock = stockData.get(itemId) || 0
      
      if (quantity > availableStock) {
        const item = articulosConStock.find((a) => a.id === itemId)
        setError(`La cantidad de ${item?.name || 'artículo'} excede el stock disponible (${availableStock.toFixed(2)})`)
        return
      }
    }
    
    setSaving(true); setError(''); setSuccess(false)
    try {
      const response = await api.post('/salidas', {
        ...form,
        warehouseId: Number(form.warehouseId),
        items: lines.map((l) => ({ itemId: Number(l.itemId), quantity: parseFloat(l.quantity) })),
      })
      
      // Obtener el ID de la salida creada
      const salidaId = response.data.id
      setSuccess(true)
      
      // Obtener el PDF usando la API con autenticación
      try {
        const pdfResponse = await api.get(`/salidas/${salidaId}/pdf`, {
          responseType: 'blob',
        })
        
        // Crear blob URL y abrir en nueva ventana para imprimir
        const blob = new Blob([pdfResponse.data], { type: 'application/pdf' })
        const pdfUrl = window.URL.createObjectURL(blob)
        
        // Abrir PDF en nueva ventana
        const printWindow = window.open(pdfUrl, '_blank')
        if (printWindow) {
          // Esperar a que el PDF cargue y luego mostrar diálogo de impresión
          setTimeout(() => {
            try {
              printWindow.print()
            } catch (printError) {
              console.log('No se pudo abrir el diálogo de impresión automáticamente')
            }
          }, 1000)
        } else {
          // Si popup está bloqueado, descargar el PDF
          const link = document.createElement('a')
          link.href = pdfUrl
          link.download = `comprobante-salida-${salidaId}.pdf`
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        }
        
        // Limpiar el blob URL después de un tiempo
        setTimeout(() => {
          window.URL.revokeObjectURL(pdfUrl)
        }, 30000)
      } catch (pdfError) {
        console.error('Error al generar PDF:', pdfError)
        // Mostrar mensaje pero continuar
        alert('La salida se creó exitosamente, pero no se pudo abrir el PDF automáticamente. Puede descargarlo desde la lista de salidas.')
      }
      
      // Redirigir a la lista de salidas después de un breve delay
      setTimeout(() => {
        router.push('/salidas')
      }, 2000)
    } catch (e: any) {
      setError(e.response?.data?.message || 'Error al crear salida')
      setSuccess(false)
    }
    finally { setSaving(false) }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-5 max-w-4xl">
      {error && <div className="bg-red-50 text-red-700 border border-red-200 rounded-lg p-3 text-sm font-medium">{error}</div>}
      {success && (
        <div className="bg-green-50 text-green-800 border border-green-200 rounded-lg p-3 text-sm font-medium">
          <span className="flex items-center gap-2">
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
            </svg>
            Salida registrada exitosamente. El comprobante se abrirá en una nueva ventana para imprimir.
          </span>
        </div>
      )}

      <div className="bg-white rounded-xl shadow-sm border p-5">
        <h3 className="font-semibold text-gray-700 mb-4">Datos del Documento</h3>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          <div>
            <label className="block text-xs font-medium text-gray-600 mb-1">Fecha *</label>
            <input type="date" required className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
              value={form.date} onChange={(e) => setForm({ ...form, date: e.target.value })} />
          </div>
          <div>
            <label className="block text-xs font-medium text-gray-600 mb-1">Proyecto *</label>
            <select required className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
              value={selectedProject} onChange={(e) => setSelectedProject(e.target.value)}>
              <option value="">Seleccionar...</option>
              {proyectos.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-xs font-medium text-gray-600 mb-1">Bodega *</label>
            <select required disabled={!selectedProject} className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400 disabled:bg-gray-100"
              value={form.warehouseId} onChange={(e) => setForm({ ...form, warehouseId: e.target.value })}>
              <option value="">Seleccionar...</option>
              {bodegas.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-xs font-medium text-gray-600 mb-1">Referencia</label>
            <input type="text" className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
              value={form.reference} onChange={(e) => setForm({ ...form, reference: e.target.value })} />
          </div>
          <div>
            <label className="block text-xs font-medium text-gray-600 mb-1">Destino</label>
            <input type="text" className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
              value={form.destination} onChange={(e) => setForm({ ...form, destination: e.target.value })} />
          </div>
          <div>
            <label className="block text-xs font-medium text-gray-600 mb-1">Beneficiario</label>
            <input type="text" className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
              value={form.beneficiary} onChange={(e) => setForm({ ...form, beneficiary: e.target.value })} />
          </div>
        </div>
      </div>

      <div className="bg-white rounded-xl shadow-sm border p-5">
        <div className="flex items-center justify-between mb-4">
          <h3 className="font-semibold text-gray-700">Artículos</h3>
          <button type="button" onClick={addLine} className="text-indigo-600 text-sm hover:underline">+ Agregar línea</button>
        </div>
        
        {/* Scanner Input */}
        <div className="mb-4 p-4 bg-blue-50 rounded-lg border border-blue-200">
          <label className="block text-sm font-bold text-gray-700 mb-2 flex items-center gap-2">
            <svg className="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M12 4v1m6 11h2m-6 0h-2v4m0-11v3m0 0h.01M12 12h4.01M16 20h4M4 12h4m12 0h.01M5 8h2a1 1 0 001-1V5a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1zm12 0h2a1 1 0 001-1V5a1 1 0 00-1-1h-2a1 1 0 00-1 1v2a1 1 0 001 1zM5 20h2a1 1 0 001-1v-2a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1z" />
            </svg>
            Escanear Código de Barras / SKU
          </label>
          <input
            type="text"
            value={scanInput}
            onChange={(e) => setScanInput(e.target.value)}
            onKeyDown={handleScan}
            placeholder="Escanee o escriba el SKU y presione Enter..."
            className="w-full border-2 border-indigo-300 rounded-lg px-4 py-3 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-all"
            disabled={scanning || !form.warehouseId || articulosConStock.length === 0}
          />
          <p className="text-xs text-gray-600 mt-2 flex items-center gap-1">
            {scanning ? (
              <>
                <svg className="w-4 h-4 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                </svg>
                Procesando...
              </>
            ) : (
              <>
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                Escanee el código de barras o escriba el SKU y presione Enter para agregar automáticamente
              </>
            )}
          </p>
        </div>
        {!form.warehouseId && (
          <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-3 text-sm text-yellow-800 mb-4">
            <p className="flex items-center gap-2">
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              Seleccione una bodega para ver los artículos con existencia disponible.
            </p>
          </div>
        )}
        {form.warehouseId && articulosConStock.length === 0 && (
          <div className="bg-gray-50 border border-gray-200 rounded-lg p-4 text-sm text-gray-600 mb-4 text-center">
            <p>No hay artículos con existencia en esta bodega.</p>
          </div>
        )}
        <div className="space-y-2">
          {lines.map((line, i) => (
            <div key={i} className="grid grid-cols-12 gap-2 items-center">
              <div className="col-span-8">
                <select required className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
                  value={line.itemId} onChange={(e) => updateLine(i, 'itemId', e.target.value)}
                  disabled={!form.warehouseId}>
                  <option value="">{form.warehouseId ? 'Artículo...' : 'Seleccione una bodega primero'}</option>
                  {articulosConStock.map((a) => (
                    <option key={a.id} value={a.id}>
                      {a.sku} — {a.name} ({a.unit}) - Stock: {a.stock?.toFixed(2) || '0.00'}
                    </option>
                  ))}
                </select>
              </div>
              <div className="col-span-3">
                <input 
                  type="number" 
                  min="0.01" 
                  step="any" 
                  required 
                  placeholder="Cantidad"
                  max={stockData.get(Number(line.itemId)) || undefined}
                  className="w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
                  value={line.quantity} 
                  onChange={(e) => updateLine(i, 'quantity', e.target.value)} 
                />
                {line.itemId && stockData.has(Number(line.itemId)) && (
                  <p className="text-xs text-gray-500 mt-1">
                    Disponible: {stockData.get(Number(line.itemId))?.toFixed(2) || '0.00'}
                  </p>
                )}
              </div>
              <div className="col-span-1 text-center">
                {lines.length > 1 && <button type="button" onClick={() => removeLine(i)} className="text-red-400 hover:text-red-600 text-lg">×</button>}
              </div>
            </div>
          ))}
        </div>
        <p className="text-xs text-gray-500 mt-3 flex items-center gap-1">
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          El costo unitario se calculará automáticamente desde el kardex (costo promedio ponderado).
        </p>
      </div>

      <div className="flex justify-end gap-3">
        <button type="button" onClick={() => router.back()} className="px-5 py-2 border rounded-lg text-sm hover:bg-gray-50">Cancelar</button>
        <button type="submit" disabled={saving} className="px-5 py-2 bg-blue-600 text-white rounded-lg text-sm hover:bg-blue-700 disabled:opacity-50 flex items-center gap-2">
          {saving ? (
            <>
              <svg className="w-4 h-4 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
              </svg>
              Guardando...
            </>
          ) : (
            <>
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
              </svg>
              Registrar Salida
            </>
          )}
        </button>
      </div>
    </form>
  )
}
