'use client'

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

export default function ImportarIngresosPage() {
  const [file, setFile] = useState<File | null>(null)
  const [skipInvalid, setSkipInvalid] = useState(false)
  const [uploading, setUploading] = useState(false)
  const [result, setResult] = useState<any>(null)
  const [error, setError] = useState('')
  const inputRef = useRef<HTMLInputElement>(null)

  const downloadTemplate = async () => {
    try {
      const r = await api.get('/excel/template/ingresos', { responseType: 'blob' })
      const url = URL.createObjectURL(new Blob([r.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
      const a = document.createElement('a')
      a.href = url
      a.download = 'plantilla-ingresos.xlsx'
      a.click()
      URL.revokeObjectURL(url)
    } catch (e) {
      setError('Error al descargar la plantilla')
    }
  }

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault()
    const dropped = e.dataTransfer.files[0]
    if (dropped && dropped.name.endsWith('.xlsx')) setFile(dropped)
    else setError('Solo se aceptan archivos .xlsx')
  }

  const handleUpload = async () => {
    if (!file) { setError('Seleccione un archivo'); return }
    setUploading(true); setError(''); setResult(null)
    try {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('skipInvalid', skipInvalid.toString())
      const r = await api.post('/excel/import/ingresos', formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
      })
      setResult(r.data)
    } catch (e: any) {
      const data = e.response?.data
      if (data?.errors) {
        setResult({ errors: data.errors.length, validationErrors: data.errors, created: 0, processed: 0 })
        setError(data.message || 'Errores de validación en el archivo')
      } else {
        setError(data?.message || 'Error al importar')
      }
    } finally { setUploading(false) }
  }

  const reset = () => { setFile(null); setResult(null); setError(''); if (inputRef.current) inputRef.current.value = '' }

  return (
    <div className="max-w-3xl w-full space-y-5">
      {/* Back + title row */}
      <div className="flex items-center gap-3">
        <Link href="/ingresos" className="text-black font-semibold hover:text-indigo-700 text-sm">← Volver a Ingresos</Link>
      </div>

      {/* Instructions card */}
      <div className="bg-indigo-50 border border-indigo-200 rounded-xl p-5">
        <h3 className="font-bold text-black mb-3 flex items-center gap-2">
          <span>📋</span> Instrucciones de importación masiva
        </h3>
        <ul className="text-sm text-black space-y-1 list-disc list-inside">
          <li>Descargue la plantilla, llénela y súbala a continuación.</li>
          <li>Cada fila representa <strong>un artículo</strong> de un ingreso.</li>
          <li>Filas con la misma <strong>Fecha + Bodega + Referencia</strong> se agrupan en un solo documento.</li>
          <li>Los códigos de Bodega, Artículo y Proveedor deben existir en el sistema.</li>
          <li>Formato de fecha: <code className="bg-white px-1 rounded">YYYY-MM-DD</code> (ej. 2024-01-15).</li>
          <li>Si activa <em>&quot;Ignorar filas con error&quot;</em>, se importarán las filas válidas y se reportarán las inválidas.</li>
        </ul>
        <button
          onClick={downloadTemplate}
          className="mt-4 inline-flex items-center gap-2 bg-indigo-600 text-white px-4 py-2 rounded-lg text-sm font-semibold hover:bg-indigo-700 transition"
        >
          <span>⬇️</span> Descargar Plantilla Excel
        </button>
      </div>

      {/* Upload area */}
      {!result && (
        <div className="bg-white rounded-xl shadow-sm border p-5 space-y-4">
          <h3 className="font-bold text-black">Subir archivo</h3>

          {/* Drop zone */}
          <div
            onDrop={handleDrop}
            onDragOver={(e) => e.preventDefault()}
            onClick={() => inputRef.current?.click()}
            className={`border-2 border-dashed rounded-xl p-8 text-center cursor-pointer transition ${
              file ? 'border-indigo-400 bg-indigo-50' : 'border-gray-300 hover:border-indigo-400 hover:bg-gray-50'
            }`}
          >
            <input
              ref={inputRef}
              type="file"
              accept=".xlsx"
              className="hidden"
              onChange={(e) => { setError(''); setFile(e.target.files?.[0] || null) }}
            />
            {file ? (
              <div>
                <p className="text-2xl mb-2">📄</p>
                <p className="font-bold text-black">{file.name}</p>
                <p className="text-sm text-gray-600 mt-1">{(file.size / 1024).toFixed(1)} KB</p>
              </div>
            ) : (
              <div>
                <p className="text-3xl mb-2">📁</p>
                <p className="font-semibold text-black">Arrastra tu archivo aquí</p>
                <p className="text-sm text-gray-600 mt-1">o haz clic para seleccionar</p>
                <p className="text-xs text-gray-500 mt-2">Solo archivos .xlsx</p>
              </div>
            )}
          </div>

          {error && <div className="bg-red-50 text-red-800 border border-red-200 rounded-lg p-3 text-sm font-semibold">{error}</div>}

          {/* Options */}
          <label className="flex items-center gap-3 cursor-pointer select-none">
            <input
              type="checkbox"
              className="w-4 h-4 accent-indigo-600"
              checked={skipInvalid}
              onChange={(e) => setSkipInvalid(e.target.checked)}
            />
            <span className="text-sm font-semibold text-black">Ignorar filas con error e importar las válidas</span>
          </label>

          {/* Actions */}
          <div className="flex flex-col sm:flex-row gap-3">
            {file && (
              <button
                type="button"
                onClick={reset}
                className="w-full sm:w-auto px-4 py-2 border rounded-lg text-sm font-semibold text-black hover:bg-gray-50"
              >
                Cambiar archivo
              </button>
            )}
            <button
              type="button"
              onClick={handleUpload}
              disabled={!file || uploading}
              className="w-full sm:w-auto flex-1 sm:flex-none px-6 py-2 bg-indigo-600 text-white rounded-lg text-sm font-semibold hover:bg-indigo-700 disabled:opacity-50 transition"
            >
              {uploading ? (
                <span className="flex items-center justify-center gap-2">
                  <span className="animate-spin inline-block w-4 h-4 border-2 border-white border-t-transparent rounded-full" />
                  Procesando...
                </span>
              ) : '🚀 Importar'}
            </button>
          </div>
        </div>
      )}

      {/* Results */}
      {result && (
        <div className="bg-white rounded-xl shadow-sm border p-5 space-y-4">
          <h3 className="font-bold text-black text-lg">Resultado de la importación</h3>

          {/* Summary */}
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
            <div className="bg-indigo-50 border border-indigo-200 rounded-lg p-3 text-center">
              <p className="text-2xl font-bold text-indigo-800">{result.processed || 0}</p>
              <p className="text-xs font-semibold text-indigo-700 mt-1">Documentos procesados</p>
            </div>
            <div className="bg-green-50 border border-green-200 rounded-lg p-3 text-center">
              <p className="text-2xl font-bold text-green-800">{result.created || 0}</p>
              <p className="text-xs font-semibold text-green-700 mt-1">Ingresos creados</p>
            </div>
            <div className={`border rounded-lg p-3 text-center ${result.errors > 0 ? 'bg-red-50 border-red-200' : 'bg-gray-50 border-gray-200'}`}>
              <p className={`text-2xl font-bold ${result.errors > 0 ? 'text-red-800' : 'text-gray-600'}`}>{result.errors || 0}</p>
              <p className={`text-xs font-semibold mt-1 ${result.errors > 0 ? 'text-red-700' : 'text-gray-600'}`}>Errores</p>
            </div>
            <div className="bg-gray-50 border border-gray-200 rounded-lg p-3 text-center">
              <p className="text-2xl font-bold text-black">{(result.created || 0) + (result.errors || 0)}</p>
              <p className="text-xs font-semibold text-gray-700 mt-1">Total filas</p>
            </div>
          </div>

          {/* Created ingresos */}
          {result.ingresos?.length > 0 && (
            <div>
              <h4 className="font-bold text-black text-sm mb-2">✅ Ingresos creados:</h4>
              <div className="overflow-x-auto">
                <table className="min-w-full text-sm border rounded-lg overflow-hidden">
                  <thead className="bg-gray-50 text-black text-xs font-bold uppercase">
                    <tr>
                      <th className="px-3 py-2 text-left">N° Documento</th>
                      <th className="px-3 py-2 text-right">Total</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-100">
                    {result.ingresos.map((ing: any) => (
                      <tr key={ing.id} className="hover:bg-gray-50">
                        <td className="px-3 py-2 font-mono text-indigo-700 font-semibold">
                          <Link href={`/ingresos/${ing.id}`} className="hover:underline">{ing.docNumber}</Link>
                        </td>
                        <td className="px-3 py-2 text-right font-semibold text-black">
                          L. {Number(ing.total).toLocaleString('es-HN', { minimumFractionDigits: 2 })}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* Validation errors */}
          {result.validationErrors?.length > 0 && (
            <div>
              <h4 className="font-bold text-red-700 text-sm mb-2">⚠️ Errores de validación:</h4>
              <div className="max-h-60 overflow-y-auto border rounded-lg">
                <table className="min-w-full text-xs">
                  <thead className="bg-red-50 text-black font-bold uppercase sticky top-0">
                    <tr>
                      <th className="px-3 py-2 text-left">Fila</th>
                      <th className="px-3 py-2 text-left">Errores</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-red-100">
                    {result.validationErrors.map((e: any, i: number) => (
                      <tr key={i} className="bg-red-50/50">
                        <td className="px-3 py-2 font-bold text-black">#{e.row}</td>
                        <td className="px-3 py-2 text-red-800">{Array.isArray(e.errors) ? e.errors.join(', ') : e.errors}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* Create errors */}
          {result.createErrors?.length > 0 && (
            <div>
              <h4 className="font-bold text-red-700 text-sm mb-2">❌ Errores al crear:</h4>
              <ul className="text-sm text-red-800 space-y-1 list-disc list-inside">
                {result.createErrors.map((e: any, i: number) => (
                  <li key={i}><strong>{e.group}</strong>: {e.error}</li>
                ))}
              </ul>
            </div>
          )}

          {/* Actions */}
          <div className="flex flex-col sm:flex-row gap-3 pt-2">
            <button onClick={reset} className="w-full sm:w-auto px-4 py-2 border rounded-lg text-sm font-semibold text-black hover:bg-gray-50">
              Importar otro archivo
            </button>
            <Link href="/ingresos" className="w-full sm:w-auto text-center px-4 py-2 bg-indigo-600 text-white rounded-lg text-sm font-semibold hover:bg-indigo-700">
              Ver Ingresos
            </Link>
          </div>
        </div>
      )}
    </div>
  )
}
