'use client'

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

export default function ReporteStockPage() {
  const [data, setData] = useState<any[]>([])
  const [loading, setLoading] = useState(false)
  const [proyectos, setProyectos] = useState<any[]>([])
  const [filters, setFilters] = useState({ projectId: '', warehouseId: '' })
  const [bodegas, setBodegas] = useState<any[]>([])

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

  useEffect(() => {
    if (filters.projectId) {
      api.get('/warehouses', { params: { projectId: filters.projectId, activeOnly: true } })
        .then((r) => setBodegas(Array.isArray(r.data) ? r.data : r.data.data ?? []))
        .catch(console.error)
    } else { setBodegas([]) }
    setFilters((f) => ({ ...f, warehouseId: '' }))
  }, [filters.projectId])

  const fetchReport = async () => {
    setLoading(true)
    try {
      const r = await api.get('/reports/stock-on-hand', { 
        params: { 
          projectId: filters.projectId || undefined, 
          warehouseId: filters.warehouseId || undefined 
        } 
      })
      setData(Array.isArray(r.data) ? r.data : r.data.data ?? [])
    } catch (e) { 
      console.error('Error fetching stock report:', e)
      setData([])
    }
    finally { setLoading(false) }
  }

  const exportExcel = async () => {
    try {
      // Por ahora, generar Excel desde los datos en memoria
      // TODO: Implementar endpoint de exportación en backend si es necesario
      alert('Funcionalidad de exportación a Excel pendiente de implementar')
    } catch (e) {
      console.error('Error exporting to Excel:', e)
    }
  }

  const totalValue = data.reduce((s, r) => s + Number(r.totalValue || 0), 0)

  return (
    <div className="space-y-4">
      <div className="bg-white rounded-xl shadow-sm border p-4">
        <div className="flex flex-wrap gap-3 items-end">
          <div>
            <label className="block text-xs text-gray-500 mb-1">Proyecto</label>
            <select className="border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
              value={filters.projectId} onChange={(e) => setFilters({ ...filters, projectId: e.target.value })}>
              <option value="">Todos</option>
              {proyectos.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-xs text-gray-500 mb-1">Bodega</label>
            <select disabled={!filters.projectId} className="border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400 disabled:bg-gray-50"
              value={filters.warehouseId} onChange={(e) => setFilters({ ...filters, warehouseId: e.target.value })}>
              <option value="">Todas</option>
              {bodegas.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}
            </select>
          </div>
          <button onClick={fetchReport} className="px-4 py-2 bg-indigo-600 text-white rounded-lg text-sm hover:bg-indigo-700">
            🔍 Generar
          </button>
          {data.length > 0 && (
            <button onClick={exportExcel} className="px-4 py-2 bg-green-600 text-white rounded-lg text-sm hover:bg-green-700">
              📥 Exportar Excel
            </button>
          )}
        </div>
      </div>

      {data.length > 0 && (
        <div className="bg-indigo-50 border border-indigo-200 rounded-xl px-5 py-3 flex items-center justify-between">
          <span className="text-sm text-indigo-700 font-medium">Valor total del inventario</span>
          <span className="text-xl font-bold text-indigo-800">L. {totalValue.toLocaleString('es-HN', { minimumFractionDigits: 2 })}</span>
        </div>
      )}

      <div className="bg-white rounded-xl shadow-sm border overflow-hidden">
        <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-left">Unidad</th>
              <th className="px-4 py-3 text-left">Bodega</th>
              <th className="px-4 py-3 text-left">Proyecto</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">Valor Total</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100">
            {loading ? (
              <tr><td colSpan={8} className="text-center py-10 text-gray-400">Generando reporte...</td></tr>
            ) : data.length === 0 ? (
              <tr><td colSpan={8} className="text-center py-10 text-gray-400">Seleccione filtros y haga clic en Generar</td></tr>
            ) : data.map((row, i) => (
              <tr key={i} className={`hover:bg-gray-50 ${Number(row.quantity) <= 0 ? 'bg-red-50/40 text-red-600' : ''}`}>
                <td className="px-4 py-2 font-mono text-xs text-gray-600">{row.item?.sku}</td>
                <td className="px-4 py-2 font-medium text-gray-800">{row.item?.name}</td>
                <td className="px-4 py-2 text-gray-500">{row.item?.unit}</td>
                <td className="px-4 py-2 text-gray-600">{row.warehouse?.name}</td>
                <td className="px-4 py-2"><span className="bg-indigo-50 text-indigo-700 px-2 py-0.5 rounded text-xs">{row.warehouse?.project?.name}</span></td>
                <td className={`px-4 py-2 text-right font-semibold ${Number(row.quantity) <= 0 ? 'text-red-600' : 'text-gray-800'}`}>
                  {Number(row.quantity).toLocaleString('es-HN', { minimumFractionDigits: 2 })}
                </td>
                <td className="px-4 py-2 text-right text-gray-700">L. {Number(row.avgCost || row.unitCost || 0).toLocaleString('es-HN', { minimumFractionDigits: 2 })}</td>
                <td className="px-4 py-2 text-right font-semibold text-indigo-700">L. {Number(row.totalValue || 0).toLocaleString('es-HN', { minimumFractionDigits: 2 })}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}
