'use client'

import { useEffect, useState } from 'react'
import api from '@/lib/api'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts'

export default function ReporteCostosPage() {
  const [data, setData] = useState<any[]>([])
  const [loading, setLoading] = useState(false)
  const [filters, setFilters] = useState({ startDate: '', endDate: '' })

  const fetchReport = async () => {
    setLoading(true)
    try {
      const r = await api.get('/reports/project-costs', {
        params: { 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/project-costs/excel', {
      params: { 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 = 'costos-por-proyecto.xlsx'; a.click()
    URL.revokeObjectURL(url)
  }

  const totalCost = data.reduce((s, r) => s + Number(r.totalCost || 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">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>
          <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">Costo total consumido (todos los proyectos)</span>
            <span className="text-xl font-bold text-indigo-800">L. {totalCost.toLocaleString('es-HN', { minimumFractionDigits: 2 })}</span>
          </div>

          <div className="bg-white rounded-xl shadow-sm border p-5">
            <h3 className="text-sm font-semibold text-gray-700 mb-4">Costo por Proyecto</h3>
            <ResponsiveContainer width="100%" height={280}>
              <BarChart data={data}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="project.name" tick={{ fontSize: 11 }} />
                <YAxis tick={{ fontSize: 11 }} tickFormatter={(v) => `L.${(v / 1000).toFixed(0)}k`} />
                <Tooltip formatter={(v: any) => `L. ${Number(v).toLocaleString('es-HN', { minimumFractionDigits: 2 })}`} />
                <Bar dataKey="totalCost" fill="#6366f1" name="Costo Total" radius={[4, 4, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </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">Proyecto</th>
              <th className="px-4 py-3 text-right">N° Salidas</th>
              <th className="px-4 py-3 text-right">Costo Total</th>
              <th className="px-4 py-3 text-right">% del Total</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100">
            {loading ? (
              <tr><td colSpan={4} className="text-center py-10 text-gray-400">Generando...</td></tr>
            ) : data.length === 0 ? (
              <tr><td colSpan={4} className="text-center py-10 text-gray-400">Seleccione período y haga clic en Generar</td></tr>
            ) : data.map((row, i) => (
              <tr key={i} className="hover:bg-gray-50">
                <td className="px-4 py-3 font-medium text-gray-800">
                  <span className="bg-indigo-50 text-indigo-700 px-2 py-0.5 rounded mr-2 text-xs">{row.project?.code}</span>
                  {row.project?.name}
                </td>
                <td className="px-4 py-3 text-right text-gray-600">{row.movementsCount || 0}</td>
                <td className="px-4 py-3 text-right font-bold text-indigo-700">L. {Number(row.totalCost).toLocaleString('es-HN', { minimumFractionDigits: 2 })}</td>
                <td className="px-4 py-3 text-right">
                  <div className="flex items-center justify-end gap-2">
                    <div className="w-24 bg-gray-200 rounded-full h-1.5">
                      <div className="bg-indigo-500 h-1.5 rounded-full" style={{ width: `${totalCost > 0 ? (Number(row.totalCost) / totalCost) * 100 : 0}%` }} />
                    </div>
                    <span className="text-gray-600 text-xs">
                      {totalCost > 0 ? ((Number(row.totalCost) / totalCost) * 100).toFixed(1) : 0}%
                    </span>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  )
}
