'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import api from '@/lib/api'
import { UploadIcon, DownloadIcon, CheckIcon, XIcon } from '@/components/Icons'

export default function ImportarArticulosPage() {
  const router = useRouter()
  const [file, setFile] = useState<File | null>(null)
  const [skipInvalid, setSkipInvalid] = useState(false)
  const [loading, setLoading] = useState(false)
  const [result, setResult] = useState<any>(null)
  const [error, setError] = useState<string | null>(null)

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files.length > 0) {
      setFile(event.target.files[0])
      setError(null)
      setResult(null)
    }
  }

  const handleDownloadTemplate = async () => {
    try {
      const response = await api.get('/excel/template/items', {
        responseType: 'blob',
      })
      
      // Create a blob from the response
      const blob = new Blob([response.data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      })
      
      // Create a temporary URL and trigger download
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', 'plantilla-articulos.xlsx')
      document.body.appendChild(link)
      link.click()
      link.remove()
      window.URL.revokeObjectURL(url)
    } catch (err: any) {
      console.error('Error downloading template:', err)
      setError('Error al descargar la plantilla. Por favor, intente nuevamente.')
    }
  }

  const handleImport = async () => {
    if (!file) {
      setError('Por favor, seleccione un archivo Excel para importar.')
      return
    }

    setLoading(true)
    setError(null)
    setResult(null)

    const formData = new FormData()
    formData.append('file', file)
    formData.append('skipInvalid', skipInvalid.toString())

    try {
      const response = await api.post('/excel/import/items', formData, {
        headers: {
          // No establecer Content-Type manualmente - axios lo hará automáticamente con el boundary correcto
        },
      })
      setResult(response.data)
      // Si hay errores, mostrarlos siempre
      if (response.data.errors > 0 || (response.data.details && response.data.details.length > 0)) {
        setError(null) // No mostrar error general si hay detalles
      }
      // Solo redirigir si no hay errores y hay artículos creados
      if (response.data.created > 0 && (response.data.errors === 0 || !response.data.details || response.data.details.length === 0)) {
        setTimeout(() => {
          router.push('/maestros/articulos')
        }, 3000)
      }
    } catch (err: any) {
      console.error('Error importing items:', err)
      const errorData = err.response?.data
      
      // Si el error tiene detalles de validación, mostrarlos en result
      if (errorData?.errors && Array.isArray(errorData.errors)) {
        setResult({
          created: 0,
          errors: errorData.errors.length,
          details: errorData.errors,
        })
        setError(null)
      } else {
        setError(errorData?.message || 'Error al importar artículos. Verifique el archivo y los datos.')
        if (errorData?.details) {
          setResult({
            created: 0,
            errors: errorData.details.length,
            details: errorData.details,
          })
        }
      }
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Importar Artículos desde Excel</h1>
          <p className="text-sm text-gray-600 mt-1">Importe múltiples artículos desde un archivo Excel</p>
        </div>
        <Link
          href="/maestros/articulos"
          className="px-4 py-2 border border-gray-300 rounded-lg text-sm font-medium text-gray-700 hover:bg-gray-50 transition"
        >
          ← Volver
        </Link>
      </div>

      {/* Instructions Card */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
          <svg className="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
          </svg>
          Instrucciones
        </h2>
        <ul className="space-y-2 text-sm text-gray-700 list-disc list-inside">
          <li>Descargue la plantilla Excel para asegurar el formato correcto</li>
          <li>Complete los campos requeridos (marcados con *)</li>
          <li>El SKU debe ser único y no puede estar duplicado en el archivo</li>
          <li>Los artículos con SKU existente serán omitidos</li>
          <li>Puede activar &quot;Omitir filas inválidas&quot; para continuar con las válidas</li>
        </ul>
      </div>

      {/* Download Template */}
      <div className="bg-blue-50 rounded-lg border border-blue-200 p-6">
        <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
          <div>
            <h3 className="text-sm font-semibold text-blue-900 mb-1 flex items-center gap-2">
              <DownloadIcon className="w-5 h-5 text-blue-600" />
              Descargar Plantilla
            </h3>
            <p className="text-xs text-blue-700">Descargue la plantilla para asegurar el formato correcto</p>
          </div>
          <button
            onClick={handleDownloadTemplate}
            className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-semibold hover:bg-blue-700 transition shadow-sm hover:shadow"
          >
            <DownloadIcon className="w-4 h-4" />
            Descargar Plantilla Excel
          </button>
        </div>
      </div>

      {/* Upload Form */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <h2 className="text-lg font-semibold text-gray-900 mb-4">Subir Archivo Excel</h2>

        <div className="space-y-4">
          <div>
            <label htmlFor="file-upload" className="block text-sm font-medium text-gray-700 mb-2">
              Seleccionar archivo Excel (.xlsx)
            </label>
            <input
              id="file-upload"
              type="file"
              accept=".xlsx,.xls"
              onChange={handleFileChange}
              className="block w-full text-sm text-gray-900
                file:mr-4 file:py-2 file:px-4
                file:rounded-lg file:border-0
                file:text-sm file:font-semibold
                file:bg-blue-50 file:text-blue-700
                hover:file:bg-blue-100
                border border-gray-300 rounded-lg p-2"
            />
            {file && (
              <p className="mt-2 text-sm text-gray-600 flex items-center gap-2">
                <CheckIcon className="w-4 h-4 text-green-600" />
                Archivo seleccionado: <span className="font-medium">{file.name}</span>
              </p>
            )}
          </div>

          <div className="flex items-center">
            <input
              id="skip-invalid"
              type="checkbox"
              checked={skipInvalid}
              onChange={(e) => setSkipInvalid(e.target.checked)}
              className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
            />
            <label htmlFor="skip-invalid" className="ml-2 block text-sm text-gray-900">
              Omitir filas inválidas (continuar importando las filas válidas)
            </label>
          </div>

          <button
            onClick={handleImport}
            disabled={!file || loading}
            className={`w-full py-2.5 px-4 rounded-lg text-sm font-semibold text-white transition flex items-center justify-center gap-2
              ${!file || loading 
                ? 'bg-gray-400 cursor-not-allowed' 
                : 'bg-blue-600 hover:bg-blue-700 shadow-sm hover:shadow'
              }`}
          >
            {loading ? (
              <>
                <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>
                Importando...
              </>
            ) : (
              <>
                <UploadIcon className="w-4 h-4" />
                Importar Artículos
              </>
            )}
          </button>
        </div>
      </div>

      {/* Error Message */}
      {error && (
        <div className="bg-red-50 border border-red-200 text-red-800 px-4 py-3 rounded-lg" role="alert">
          <div className="flex items-center gap-2">
            <XIcon className="w-5 h-5 text-red-600" />
            <div>
              <strong className="font-bold">Error:</strong>
              <span className="block sm:inline ml-1">{error}</span>
            </div>
          </div>
        </div>
      )}

      {/* Success/Result Message */}
      {result && (
        <div className={`rounded-lg border px-4 py-3 ${
          result.errors > 0 && result.created === 0
            ? 'bg-red-50 border-red-200 text-red-800'
            : result.errors > 0
            ? 'bg-yellow-50 border-yellow-200 text-yellow-800'
            : 'bg-green-50 border-green-200 text-green-800'
        }`} role="alert">
          <div className="flex items-start gap-2">
            {result.errors > 0 && result.created === 0 ? (
              <XIcon className="w-5 h-5 text-red-600 mt-0.5 flex-shrink-0" />
            ) : result.errors > 0 ? (
              <svg className="w-5 h-5 text-yellow-600 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
              </svg>
            ) : (
              <CheckIcon className="w-5 h-5 text-green-600 mt-0.5 flex-shrink-0" />
            )}
            <div className="flex-1">
              <strong className="font-bold">
                {result.errors > 0 && result.created === 0
                  ? 'Error en la Importación'
                  : result.errors > 0
                  ? 'Importación Parcial'
                  : 'Importación Exitosa'}
              </strong>
              <div className="mt-2 space-y-3 text-sm">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <span className="font-semibold">Artículos creados:</span>{' '}
                    <span className={result.created > 0 ? 'text-green-700 font-bold' : 'text-gray-700'}>
                      {result.created || 0}
                    </span>
                  </div>
                  <div>
                    <span className="font-semibold">Errores encontrados:</span>{' '}
                    <span className={result.errors > 0 ? 'text-red-700 font-bold' : 'text-gray-700'}>
                      {result.errors || 0}
                    </span>
                  </div>
                </div>
                
                {result.details && result.details.length > 0 && (
                  <div className="mt-3">
                    <p className="font-semibold mb-2 text-base">Detalles de Errores de Validación:</p>
                    <div className="bg-white rounded border border-gray-300 overflow-hidden">
                      <div className="max-h-96 overflow-y-auto">
                        <table className="min-w-full divide-y divide-gray-200 text-xs">
                          <thead className="bg-gray-100 sticky top-0">
                            <tr>
                              <th className="px-3 py-2 text-left font-semibold text-gray-700 border-r border-gray-300">
                                Fila
                              </th>
                              <th className="px-3 py-2 text-left font-semibold text-gray-700">
                                Errores
                              </th>
                            </tr>
                          </thead>
                          <tbody className="bg-white divide-y divide-gray-200">
                            {result.details.map((detail: any, index: number) => (
                              <tr key={index} className="hover:bg-gray-50">
                                <td className="px-3 py-2 font-medium text-gray-900 border-r border-gray-200">
                                  {detail.row}
                                </td>
                                <td className="px-3 py-2 text-gray-700">
                                  {Array.isArray(detail.errors) ? (
                                    <ul className="list-disc list-inside space-y-1">
                                      {detail.errors.map((error: string, errIndex: number) => (
                                        <li key={errIndex} className="text-red-600">
                                          {error}
                                        </li>
                                      ))}
                                    </ul>
                                  ) : (
                                    <span className="text-red-600">{detail.errors}</span>
                                  )}
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    </div>
                    <p className="mt-2 text-xs text-gray-600 italic">
                      {result.details.length} {result.details.length === 1 ? 'fila con error' : 'filas con errores'}
                    </p>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
