'use client'

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

export default function IngresosPage() {
  const [ingresos, setIngresos] = useState<any[]>([])
  const [loading, setLoading] = useState(true)
  const [pagination, setPagination] = useState({ page: 1, total: 0, totalPages: 1 })
  const [filters, setFilters] = useState({ startDate: '', endDate: '', projectId: '' })
  const [proyectos, setProyectos] = useState<any[]>([])

  const fetchIngresos = async (page = 1) => {
    setLoading(true)
    try {
      const r = await api.get('/ingresos', {
        params: {
          page,
          limit: 20,
          projectId: filters.projectId || undefined,
          startDate: filters.startDate || undefined,
          endDate: filters.endDate || undefined,
        },
      })
      setIngresos(r.data.data)
      setPagination(r.data.pagination)
    } catch (e) { console.error(e) }
    finally { setLoading(false) }
  }

  useEffect(() => {
    api.get('/projects', { params: { activeOnly: true } }).then((r) => setProyectos(r.data))
    fetchIngresos()
  }, [])

  const handleCancel = async (id: number) => {
    if (!confirm('¿Cancelar este ingreso? Se revertirá el kardex.')) return
    await api.patch(`/ingresos/${id}/cancel`)
    fetchIngresos(pagination.page)
  }

  const statusBadge = (status: string) => {
    const map: any = {
      completed: 'bg-green-100 text-green-700',
      cancelled: 'bg-red-100 text-red-700',
      draft: 'bg-gray-100 text-gray-600',
    }
    const labels: any = { completed: 'Completado', cancelled: 'Cancelado', draft: 'Borrador' }
    return <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${map[status] || ''}`}>{labels[status] || status}</span>
  }

  return (
    <div className="space-y-4">
      {/* Filters + Actions */}
      <div className="bg-white rounded-xl shadow-sm border p-4">
        <div className="flex flex-wrap gap-3 items-end justify-between">
          <div className="flex flex-wrap gap-3">
            <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">Fecha 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">Fecha 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>
            <div className="flex items-end">
              <button onClick={() => fetchIngresos(1)} className="px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-lg text-sm transition">
                🔍 Buscar
              </button>
            </div>
          </div>
          <div className="flex flex-col sm:flex-row gap-2">
            <Link href="/ingresos/importar" className="text-center bg-white border border-indigo-600 text-indigo-700 font-semibold px-4 py-2 rounded-lg text-sm hover:bg-indigo-50 transition">
              📥 Importar Excel
            </Link>
            <Link href="/ingresos/nuevo" className="text-center bg-indigo-600 text-white font-semibold px-4 py-2 rounded-lg text-sm hover:bg-indigo-700 transition">
              + Nuevo Ingreso
            </Link>
          </div>
        </div>
      </div>

      {/* Table */}
      <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">N° Documento</th>
              <th className="px-4 py-3 text-left">Fecha</th>
              <th className="px-4 py-3 text-left">Proyecto</th>
              <th className="px-4 py-3 text-left">Bodega</th>
              <th className="px-4 py-3 text-left">Proveedor</th>
              <th className="px-4 py-3 text-right">Total</th>
              <th className="px-4 py-3 text-center">Estado</th>
              <th className="px-4 py-3 text-center">Acciones</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100">
            {loading ? (
              <tr><td colSpan={8} className="text-center py-10 text-gray-400">Cargando...</td></tr>
            ) : ingresos.length === 0 ? (
              <tr><td colSpan={8} className="text-center py-10 text-gray-400">No hay ingresos</td></tr>
            ) : ingresos.map((ing) => (
              <tr key={ing.id} className="hover:bg-gray-50">
                <td className="px-4 py-3 font-mono text-indigo-600">
                  <Link href={`/ingresos/${ing.id}`} className="hover:underline">{ing.docNumber}</Link>
                </td>
                <td className="px-4 py-3 text-gray-600">{new Date(ing.date).toLocaleDateString('es-HN')}</td>
                <td className="px-4 py-3"><span className="bg-indigo-50 text-indigo-700 px-2 py-0.5 rounded text-xs">{ing.project?.name}</span></td>
                <td className="px-4 py-3 text-gray-700">{ing.warehouse?.name}</td>
                <td className="px-4 py-3 text-gray-600">{ing.supplier || '—'}</td>
                <td className="px-4 py-3 text-right font-medium">
                  {ing.currency} {Number(ing.total).toLocaleString('es-HN', { minimumFractionDigits: 2 })}
                </td>
                <td className="px-4 py-3 text-center">{statusBadge(ing.status)}</td>
                <td className="px-4 py-3 text-center space-x-2">
                  <Link href={`/ingresos/${ing.id}`} className="text-indigo-600 hover:underline text-xs">Ver</Link>
                  {ing.status === 'completed' && (
                    <button onClick={() => handleCancel(ing.id)} className="text-red-500 hover:underline text-xs">Cancelar</button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>

        {/* Pagination */}
        {pagination.totalPages > 1 && (
          <div className="flex justify-center items-center gap-3 py-4 border-t text-sm">
            <button disabled={pagination.page <= 1} onClick={() => fetchIngresos(pagination.page - 1)} className="px-3 py-1 border rounded disabled:opacity-40 hover:bg-gray-50">
              ← Anterior
            </button>
            <span className="text-gray-600">Página {pagination.page} de {pagination.totalPages}</span>
            <button disabled={pagination.page >= pagination.totalPages} onClick={() => fetchIngresos(pagination.page + 1)} className="px-3 py-1 border rounded disabled:opacity-40 hover:bg-gray-50">
              Siguiente →
            </button>
          </div>
        )}
      </div>
    </div>
  )
}
