'use client'

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

export default function ReporteMovimientosPage() {
  const [data, setData] = useState<any[]>([])
  const [loading, setLoading] = useState(false)
  const [proyectos, setProyectos] = useState<any[]>([])
  const [articulos, setArticulos] = useState<any[]>([])
  const [filters, setFilters] = useState({ projectId: '', itemId: '', startDate: '', endDate: '' })

  useEffect(() => {
    Promise.all([
      api.get('/projects', { params: { activeOnly: true } }),
      api.get('/items', { params: { activeOnly: true } }),
    ]).then(([rp, ri]) => { setProyectos(rp.data); setArticulos(ri.data) })
  }, [])

  const fetchReport = async () => {
    setLoading(true)
    try {
      const r = await api.get('/reports/movements', {
        params: { projectId: filters.projectId || undefined, itemId: filters.itemId || undefined, startDate: filters.startDate || undefined, endDate: filters.endDate || undefined },
      })
      setData(r.data)
    } catch (e) { console.error(e) }
    finally { setLoading(false) }
  }

  const exportExcel = async () => {
    const r = await api.get('/reports/movements/excel', {
      params: { projectId: filters.projectId || undefined, itemId: filters.itemId || undefined, startDate: filters.startDate || undefined, endDate: filters.endDate || undefined },
      responseType: 'blob',
    })
    const url = URL.createObjectURL(new Blob([r.data]))
    const a = document.createElement('a'); a.href = url; a.download = 'movimientos.xlsx'; a.click()
    URL.revokeObjectURL(url)
  }

  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">Artículo</label>
            <select className="border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
              value={filters.itemId} onChange={(e) => setFilters({ ...filters, itemId: e.target.value })}>
              <option value="">Todos</option>
              {articulos.map((a) => <option key={a.id} value={a.id}>{a.name}</option>)}
            </select>
          </div>
          <div>
            <label className="block text-xs text-gray-500 mb-1">Desde</label>
            <input type="date" className="border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
              value={filters.startDate} onChange={(e) => setFilters({ ...filters, startDate: e.target.value })} />
          </div>
          <div>
            <label className="block text-xs text-gray-500 mb-1">Hasta</label>
            <input type="date" className="border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-400"
              value={filters.endDate} onChange={(e) => setFilters({ ...filters, endDate: e.target.value })} />
          </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>

      <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">Fecha</th>
              <th className="px-4 py-3 text-center">Tipo</th>
              <th className="px-4 py-3 text-left">Artículo</th>
              <th className="px-4 py-3 text-left">Bodega</th>
              <th className="px-4 py-3 text-left">N° Doc.</th>
              <th className="px-4 py-3 text-right">Entrada</th>
              <th className="px-4 py-3 text-right">Salida</th>
              <th className="px-4 py-3 text-right">Costo Unit.</th>
              <th className="px-4 py-3 text-right">Saldo</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100">
            {loading ? (
              <tr><td colSpan={9} className="text-center py-10 text-gray-400">Generando...</td></tr>
            ) : data.length === 0 ? (
              <tr><td colSpan={9} className="text-center py-10 text-gray-400">Seleccione filtros y haga clic en Generar</td></tr>
            ) : data.map((e, i) => (
              <tr key={i} className="hover:bg-gray-50">
                <td className="px-4 py-2 text-gray-600">{new Date(e.date).toLocaleDateString('es-HN')}</td>
                <td className="px-4 py-2 text-center">
                  <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${e.movementType === 'in' ? 'bg-green-100 text-green-700' : e.movementType === 'out' ? 'bg-orange-100 text-orange-700' : 'bg-red-100 text-red-700'}`}>
                    {e.movementType === 'in' ? 'Entrada' : e.movementType === 'out' ? 'Salida' : 'Cancelación'}
                  </span>
                </td>
                <td className="px-4 py-2 text-gray-800">{e.item?.name}</td>
                <td className="px-4 py-2 text-gray-600">{e.warehouse?.name}</td>
                <td className="px-4 py-2 font-mono text-xs text-indigo-600">{e.docRef}</td>
                <td className="px-4 py-2 text-right text-green-700">{Number(e.qtyIn) > 0 ? Number(e.qtyIn).toFixed(2) : '—'}</td>
                <td className="px-4 py-2 text-right text-orange-700">{Number(e.qtyOut) > 0 ? Number(e.qtyOut).toFixed(2) : '—'}</td>
                <td className="px-4 py-2 text-right text-gray-700">L. {Number(e.unitCost).toFixed(2)}</td>
                <td className="px-4 py-2 text-right font-semibold text-gray-800">{Number(e.balanceQty).toFixed(2)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}
