'use client'

import { useEffect, useState } from 'react'
import api from '@/lib/api'
import { ChartIcon, InventoryIcon, DollarIcon, SearchIcon, BuildingIcon, BoxIcon } from '@/components/Icons'

export default function SalidasProyectoPage() {
  const [proyectos, setProyectos] = useState<any[]>([])
  const [selectedProject, setSelectedProject] = useState('')
  const [data, setData] = useState<any>(null)
  const [loading, setLoading] = useState(false)
  const [expandedItems, setExpandedItems] = useState<Set<number>>(new Set())

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

  const fetchReport = async () => {
    if (!selectedProject) {
      alert('Seleccione un proyecto')
      return
    }
    setLoading(true)
    try {
      const r = await api.get('/reports/project-withdrawals', { 
        params: { projectId: selectedProject } 
      })
      setData(r.data)
    } catch (e: any) {
      console.error('Error fetching report:', e)
      alert(e.response?.data?.message || 'Error al generar el reporte')
      setData(null)
    }
    finally { setLoading(false) }
  }

  const toggleItem = (itemId: number) => {
    const newExpanded = new Set(expandedItems)
    if (newExpanded.has(itemId)) {
      newExpanded.delete(itemId)
    } else {
      newExpanded.add(itemId)
    }
    setExpandedItems(newExpanded)
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="bg-gradient-to-r from-blue-600 to-blue-700 rounded-lg shadow-md p-6 text-white">
        <div className="flex items-center gap-3 mb-2">
          <ChartIcon className="w-8 h-8" />
          <h1 className="text-3xl font-bold">Reporte de Salidas por Proyecto</h1>
        </div>
        <p className="text-blue-100">Detalle completo de materiales retirados del proyecto</p>
      </div>

      {/* Filters */}
      <div className="bg-white rounded-xl shadow-md border border-gray-200 p-6">
        <div className="flex flex-col sm:flex-row gap-4 items-end">
          <div className="flex-1">
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              Proyecto *
            </label>
            <select
              className="w-full border-2 border-gray-300 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition"
              value={selectedProject}
              onChange={(e) => setSelectedProject(e.target.value)}
            >
              <option value="">Seleccionar proyecto...</option>
              {proyectos.map((p) => (
                <option key={p.id} value={p.id}>{p.name}</option>
              ))}
            </select>
          </div>
          <button
            onClick={fetchReport}
            disabled={!selectedProject || loading}
            className="px-6 py-2.5 bg-blue-600 text-white rounded-lg font-semibold hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition shadow-sm hover:shadow"
          >
            {loading ? (
              <span className="flex items-center gap-2">
                <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>
                Generando...
              </span>
            ) : (
              <span className="flex items-center gap-2">
                <SearchIcon className="w-4 h-4" />
                Generar Reporte
              </span>
            )}
          </button>
        </div>
      </div>

      {/* Summary Cards */}
      {data && (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="bg-blue-50 rounded-lg p-6 border border-blue-200 shadow-sm">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-blue-600 mb-1">Total de Artículos</p>
                <p className="text-3xl font-bold text-blue-900">{data.summary.totalItems}</p>
              </div>
              <InventoryIcon className="w-10 h-10 text-blue-600" />
            </div>
          </div>
          <div className="bg-green-50 rounded-lg p-6 border border-green-200 shadow-sm">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-green-600 mb-1">Cantidad Total</p>
                <p className="text-3xl font-bold text-green-900">
                  {data.summary.totalQuantity.toLocaleString('es-HN', { minimumFractionDigits: 2 })}
                </p>
              </div>
              <ChartIcon className="w-10 h-10 text-green-600" />
            </div>
          </div>
          <div className="bg-purple-50 rounded-lg p-6 border border-purple-200 shadow-sm">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-purple-600 mb-1">Costo Total</p>
                <p className="text-3xl font-bold text-purple-900">
                  L. {data.summary.totalCost.toLocaleString('es-HN', { minimumFractionDigits: 2 })}
                </p>
              </div>
              <DollarIcon className="w-10 h-10 text-purple-600" />
            </div>
          </div>
        </div>
      )}

      {/* Project Info */}
      {data?.project && (
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <h2 className="text-xl font-bold text-gray-800 mb-4 flex items-center gap-2">
            <BuildingIcon className="w-6 h-6 text-blue-600" />
            {data.project.name}
          </h2>
          {data.project.description && (
            <p className="text-gray-600 mb-2">{data.project.description}</p>
          )}
          <p className="text-sm text-gray-500">
            <span className="font-semibold">Código:</span> {data.project.code}
          </p>
        </div>
      )}

      {/* Items Table */}
      {data && (
        <div className="bg-white rounded-xl shadow-md border border-gray-200 overflow-hidden">
          <div className="px-6 py-4 bg-gradient-to-r from-gray-50 to-gray-100 border-b border-gray-200">
            <h3 className="text-lg font-bold text-gray-800">Detalle de Artículos Retirados</h3>
          </div>
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Artículo</th>
                  <th className="px-6 py-3 text-right text-xs font-bold text-gray-700 uppercase tracking-wider">Cantidad Total</th>
                  <th className="px-6 py-3 text-right text-xs font-bold text-gray-700 uppercase tracking-wider">Costo Unit. Prom.</th>
                  <th className="px-6 py-3 text-right text-xs font-bold text-gray-700 uppercase tracking-wider">Costo Total</th>
                  <th className="px-6 py-3 text-center text-xs font-bold text-gray-700 uppercase tracking-wider">Movimientos</th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {data.items.length === 0 ? (
                  <tr>
                    <td colSpan={5} className="px-6 py-10 text-center text-gray-500">
                      No se encontraron salidas para este proyecto
                    </td>
                  </tr>
                ) : (
                  data.items.map((item: any, idx: number) => (
                    <>
                      <tr key={item.item.id} className="hover:bg-gray-50 transition">
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="flex items-center">
                            <div className="flex-shrink-0 h-10 w-10 bg-blue-100 rounded-lg flex items-center justify-center mr-3">
                              <BoxIcon className="w-5 h-5 text-blue-600" />
                            </div>
                            <div>
                              <div className="text-sm font-bold text-gray-900">{item.item.name}</div>
                              <div className="text-xs text-gray-500 font-mono">{item.item.sku}</div>
                              {item.item.unit && (
                                <div className="text-xs text-gray-400">Unidad: {item.item.unit}</div>
                              )}
                            </div>
                          </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-right">
                          <span className="text-sm font-semibold text-gray-900">
                            {item.totalQuantity.toLocaleString('es-HN', { minimumFractionDigits: 2 })}
                          </span>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-right">
                          <span className="text-sm text-gray-700">
                            L. {item.averageUnitCost.toLocaleString('es-HN', { minimumFractionDigits: 2 })}
                          </span>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-right">
                          <span className="text-sm font-bold text-indigo-700">
                            L. {item.totalCost.toLocaleString('es-HN', { minimumFractionDigits: 2 })}
                          </span>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-center">
                          <button
                            onClick={() => toggleItem(item.item.id)}
                            className="px-3 py-1.5 bg-indigo-100 text-indigo-700 rounded-lg text-xs font-semibold hover:bg-indigo-200 transition"
                          >
                            {expandedItems.has(item.item.id) ? '▲ Ocultar' : '▼ Ver'} ({item.movements.length})
                          </button>
                        </td>
                      </tr>
                      {expandedItems.has(item.item.id) && (
                        <tr key={`${item.item.id}-detail`} className="bg-gray-50">
                          <td colSpan={5} className="px-6 py-4">
                            <div className="space-y-2">
                              <h4 className="font-semibold text-gray-700 mb-3">Historial de Movimientos:</h4>
                              <div className="overflow-x-auto">
                                <table className="min-w-full text-xs">
                                  <thead className="bg-gray-100">
                                    <tr>
                                      <th className="px-3 py-2 text-left">Fecha</th>
                                      <th className="px-3 py-2 text-left">Documento</th>
                                      <th className="px-3 py-2 text-left">Bodega</th>
                                      <th className="px-3 py-2 text-right">Cantidad</th>
                                      <th className="px-3 py-2 text-right">Costo Unit.</th>
                                      <th className="px-3 py-2 text-right">Total</th>
                                      <th className="px-3 py-2 text-left">Usuario</th>
                                    </tr>
                                  </thead>
                                  <tbody className="divide-y divide-gray-200">
                                    {item.movements.map((mov: any, movIdx: number) => (
                                      <tr key={movIdx} className="hover:bg-white">
                                        <td className="px-3 py-2">{new Date(mov.date).toLocaleDateString('es-HN')}</td>
                                        <td className="px-3 py-2 font-mono text-xs">{mov.docRef}</td>
                                        <td className="px-3 py-2">{mov.warehouse?.name}</td>
                                        <td className="px-3 py-2 text-right">{mov.quantity.toLocaleString('es-HN', { minimumFractionDigits: 2 })}</td>
                                        <td className="px-3 py-2 text-right">L. {mov.unitCost.toLocaleString('es-HN', { minimumFractionDigits: 2 })}</td>
                                        <td className="px-3 py-2 text-right font-semibold">L. {mov.totalCost.toLocaleString('es-HN', { minimumFractionDigits: 2 })}</td>
                                        <td className="px-3 py-2">{mov.user?.name || '—'}</td>
                                      </tr>
                                    ))}
                                  </tbody>
                                </table>
                              </div>
                            </div>
                          </td>
                        </tr>
                      )}
                    </>
                  ))
                )}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  )
}
