import '../assets/animate-fade-in-fast.css';
import React, { useState, useEffect, useLayoutEffect, useRef } from 'react';
// Endpoint de credenciales VUCEM


import { fetchWithAuth } from '../fetchWithAuth';
const API_URL = import.meta.env.VITE_EFC_API_URL;

// Animación fade-in/slide-up para bloques (igual que Expedientes)
const fadeInSlideUp = `@keyframes fadein-slideup { 0% { opacity: 0; transform: translateY(40px); } 100% { opacity: 1; transform: translateY(0); } }`;
if (typeof document !== 'undefined' && !document.getElementById('fadein-slideup-importers')) {
  const style = document.createElement('style');
  style.id = 'fadein-slideup-importers';
  style.innerHTML = fadeInSlideUp;
  document.head.appendChild(style);
}
const VUCEM_CREDENTIALS_URL = `${API_URL}/vucem/vucem/`;
export default function Importers() {
  const focusKeeperRef = useRef(null);
  const [importers, setImporters] = useState([]);
  const [modalOpen, setModalOpen] = useState(false);
  const [modalMode, setModalMode] = useState('create'); // 'create' | 'edit' | 'view' | 'delete'
  const [modalData, setModalData] = useState({ rfc: '', nombre: '', organizacion: '' });
  const [modalLoading, setModalLoading] = useState(false);
  const [editId, setEditId] = useState(null);
  const [errorMsg, setErrorMsg] = useState('');
  const openViewModal = (importer) => {
    setModalMode('view');
    setModalData({ rfc: importer.rfc, nombre: importer.nombre, organizacion: importer.organizacion });
    setModalOpen(true);
  };
  const openEditModal = (importer) => {
    setModalMode('edit');
    setModalData({ rfc: importer.rfc, nombre: importer.nombre, organizacion: importer.organizacion });
    setEditId(importer.rfc);
    setErrorMsg('');
    setModalOpen(true);
  };
  const closeModal = () => {
    setModalOpen(false);
    setModalData({ rfc: '', nombre: '', organizacion: '' });
    setEditId(null);
    setErrorMsg('');
  };
  const handleModalChange = e => {
    const { name, value } = e.target;
    setModalData(prev => ({ ...prev, [name]: value }));
  };
  const openDeleteModal = (importer) => {
    setModalMode('delete');
    setModalData({ rfc: importer.rfc, nombre: importer.nombre, organizacion: importer.organizacion });
    setModalOpen(true);
  };

  const handleDeleteConfirm = async () => {
    setModalLoading(true);
    try {
      const res = await fetchWithAuth(`${API_URL}/customs/importadores/${modalData.rfc}/`, { method: 'DELETE' });
      if (!res.ok) throw new Error('Error al eliminar importador');
      // Refrescar lista
      const res2 = await fetchWithAuth(`${API_URL}/customs/importadores/`);
      if (!res2.ok) throw new Error('Error al obtener importadores');
      const data = await res2.json();
      setImporters(Array.isArray(data) ? data : []);
      closeModal();
    } catch {
      setErrorMsg('Error al eliminar importador');
    } finally {
      setModalLoading(false);
    }
  };
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [showAnimation, setShowAnimation] = useState(false);
  const [hasAnimated, setHasAnimated] = useState(false);

  useLayoutEffect(() => { setShowAnimation(true); }, []);
  useEffect(() => {
    if (showAnimation && !hasAnimated) {
      const timeout = setTimeout(() => {
        setHasAnimated(true);
        setShowAnimation(false);
      }, 700);
      return () => clearTimeout(timeout);
    }
  }, [showAnimation, hasAnimated]);

  useEffect(() => {
    setLoading(true);
    fetchWithAuth(`${API_URL}/customs/importadores/`)
      .then(async res => {
        if (!res.ok) throw new Error('Error al obtener importadores');
        const data = await res.json();
        setImporters(Array.isArray(data) ? data : []);
      })
      .catch(() => setImporters([]))
      .finally(() => setLoading(false));
  }, []);

  const filteredImporters = importers.filter(importer =>
    (importer.nombre || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
    (importer.rfc || '').toLowerCase().includes(searchTerm.toLowerCase())
  );

  // Paginación
  const totalImporters = filteredImporters.length;
  const totalPages = Math.ceil(totalImporters / itemsPerPage) || 1;
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const currentImporters = filteredImporters.slice(startIndex, endIndex);

  useEffect(() => { setCurrentPage(1); }, [searchTerm]);

  const handlePageChange = (page, e) => {
    if (e && typeof e.preventDefault === 'function') e.preventDefault();
    if (e && typeof e.stopPropagation === 'function') e.stopPropagation();
    if (page < 1 || page > totalPages || page === currentPage) return;
    setCurrentPage(page);
    if (typeof document !== 'undefined' && document.activeElement instanceof HTMLElement) {
      document.activeElement.blur();
    }
  };
  useLayoutEffect(() => { if (focusKeeperRef.current) focusKeeperRef.current.focus(); }, [currentPage]);
  const handleItemsPerPageChange = (newItemsPerPage) => { setItemsPerPage(newItemsPerPage); setCurrentPage(1); };
  // No hay status real en el endpoint, así que lo dejamos azul
  const getStatusBadge = () => 'bg-blue-100 text-blue-800 border border-blue-200';

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-100 p-4 sm:p-6 lg:p-8">
      <div ref={focusKeeperRef} tabIndex={-1} style={{ position: 'absolute', width: 0, height: 0, overflow: 'hidden', outline: 'none' }} aria-hidden="true"></div>
      <div className="max-w-7xl mx-auto">
        {/* Header animado y decorativo */}
        <div className={
          "mb-6 sm:mb-8 relative overflow-hidden rounded-3xl shadow-2xl bg-gradient-to-r from-blue-600 via-blue-700 to-blue-800 p-4 sm:p-8 flex flex-col sm:flex-row items-start sm:items-center gap-4 sm:gap-6" +
          (showAnimation && !hasAnimated ? ' animate-fadein-slideup opacity-0' : '')
        }
          style={showAnimation && !hasAnimated ? { animation: 'fadein-slideup 0.7s cubic-bezier(0.22,1,0.36,1) 0.05s forwards' } : undefined}>
          <div className="flex-shrink-0 bg-white/20 backdrop-blur-sm rounded-full p-3 sm:p-4 shadow-lg animate-bounce-slow">
            <svg className="h-8 w-8 sm:h-10 sm:w-10 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
            </svg>
          </div>
          <div className="flex-1 min-w-0">
            <h1 className="text-2xl sm:text-3xl lg:text-4xl font-extrabold text-white tracking-tight mb-1 flex flex-col sm:flex-row sm:items-center gap-2">
              <span>Importadores</span>
              {totalImporters > 0 && (
                <span className="inline-block bg-white/20 backdrop-blur-sm text-white text-xs sm:text-sm font-semibold px-3 py-1 rounded-full shadow-lg animate-fade-in">
                  {totalImporters} registros
                </span>
              )}
            </h1>
            <p className="text-sm sm:text-lg text-blue-100 font-medium leading-relaxed">Gestiona y supervisa las empresas importadoras registradas en el sistema.</p>
          </div>
          {/* Efectos decorativos de fondo modernos */}
          <div className="absolute -top-10 -right-10 opacity-20 pointer-events-none select-none">
            <div className="w-32 h-32 bg-white/10 rounded-full blur-xl"></div>
          </div>
          <div className="absolute -bottom-6 -left-6 opacity-15 pointer-events-none select-none">
            <div className="w-24 h-24 bg-white/10 rounded-full blur-lg"></div>
          </div>
          {/* Partículas flotantes */}
          <div className="absolute inset-0 overflow-hidden pointer-events-none">
            <div className="absolute top-1/4 left-1/4 w-2 h-2 bg-white/30 rounded-full animate-ping"></div>
            <div className="absolute top-3/4 right-1/3 w-1 h-1 bg-white/40 rounded-full animate-pulse"></div>
            <div className="absolute top-1/2 right-1/4 w-3 h-3 bg-white/20 rounded-full animate-bounce"></div>
          </div>
        </div>
        <style>{`
          @keyframes bounce-slow {
            0%, 100% { transform: translateY(0) scale(1); }
            50% { transform: translateY(-8px) scale(1.05); }
          }
          .animate-bounce-slow {
            animation: bounce-slow 3s infinite;
          }
          @keyframes fade-in {
            from { opacity: 0; transform: scale(0.9) translateY(10px); }
            to { opacity: 1; transform: scale(1) translateY(0); }
          }
          .animate-fade-in {
            animation: fade-in 0.8s ease-out;
          }
        `}</style>

        {/* Filtros y acciones */}
        <div className={
          "bg-white shadow-2xl rounded-3xl border border-gray-100 overflow-hidden w-full" +
          (showAnimation && !hasAnimated ? ' animate-fadein-slideup opacity-0' : '')
        }
          style={showAnimation && !hasAnimated ? { animation: 'fadein-slideup 0.7s cubic-bezier(0.22,1,0.36,1) 0.15s forwards' } : undefined}>
          <div className="px-4 sm:px-6 py-4 sm:py-6 border-b border-gray-200 bg-gradient-to-r from-gray-50 to-blue-50/30">
            <div className="mb-4 sm:mb-6">
              <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-3">
                <h3 className="text-sm font-semibold text-gray-800 flex items-center">
                  <svg className="w-4 h-4 mr-2 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.414A1 1 0 013 6.707V4z" />
                  </svg>
                  Filtros de búsqueda
                </h3>
                <button
                  type="button"
                  onClick={() => {
                    setModalMode('create');
                    setModalData({ rfc: '', nombre: '', organizacion: '' });
                    setErrorMsg('');
                    setModalOpen(true);
                  }}
                  className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white font-semibold text-xs sm:text-sm shadow-md transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
                >
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                  </svg>
                  Crear importador
                </button>
              </div>
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3 sm:gap-4 w-full">
                <div className="flex flex-col">
                  <label className="text-xs font-semibold text-gray-700 mb-1.5">Buscar</label>
                  <input
                    type="text"
                    value={searchTerm}
                    onChange={e => setSearchTerm(e.target.value)}
                    placeholder="Buscar importador, RFC, email..."
                    className="w-full border border-gray-300 rounded-xl px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white shadow-sm transition-all duration-200 hover:shadow-md"
                  />
                </div>
              </div>
            </div>
          </div>

          {/* Tabla de importadores */}
          <div className="overflow-x-auto w-full">
            <table className="min-w-full divide-y divide-gray-200 text-xs sm:text-sm">
              <thead className="bg-gradient-to-r from-gray-50 to-gray-100">
                <tr>
                  <th className="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">RFC</th>
                  <th className="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Nombre</th>
                  <th className="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Organización</th>
                  <th className="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Creado</th>
                  <th className="px-6 py-4 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">Actualizado</th>
                  <th className="relative px-6 py-4"><span className="sr-only">Acciones</span></th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {currentImporters.map((importer, index) => (
                  <tr key={importer.rfc} className={`hover:bg-blue-50 transition-colors duration-200 ${index % 2 === 0 ? 'bg-white' : 'bg-blue-50'} text-xs sm:text-sm`}>
                    <td className="px-4 sm:px-6 py-3 whitespace-nowrap font-medium text-gray-900 break-all max-w-[120px] sm:max-w-none">{importer.rfc}</td>
                    <td className="px-4 sm:px-6 py-3 whitespace-nowrap text-gray-900 break-all max-w-[120px] sm:max-w-none">{importer.nombre || <span className="italic text-gray-400">Sin nombre</span>}</td>
                    <td className="px-4 sm:px-6 py-3 whitespace-nowrap text-xs text-gray-700 font-mono break-all max-w-[120px] sm:max-w-none">{importer.organizacion}</td>
                    <td className="px-4 sm:px-6 py-3 whitespace-nowrap text-xs text-gray-500">{importer.created_at ? new Date(importer.created_at).toLocaleString() : ''}</td>
                    <td className="px-4 sm:px-6 py-3 whitespace-nowrap text-xs text-gray-500">{importer.updated_at ? new Date(importer.updated_at).toLocaleString() : ''}</td>
                    <td className="px-4 sm:px-6 py-3 whitespace-nowrap text-right font-medium">
                      <div className="flex items-center justify-end space-x-1 sm:space-x-2">
                        <button
                          className="inline-flex items-center justify-center p-2 rounded-full bg-blue-50 hover:bg-blue-100 text-blue-700 transition-all focus:outline-none"
                          title="Ver"
                          aria-label="Ver"
                          onClick={() => openViewModal(importer)}
                        >
                          <svg xmlns="http://www.w3.org/2000/svg" className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                            <path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.477 0 8.268 2.943 9.542 7-1.274 4.057-5.065 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                          </svg>
                        </button>
                        <button
                          className="inline-flex items-center justify-center p-2 rounded-full bg-yellow-50 hover:bg-yellow-100 text-yellow-700 transition-all focus:outline-none"
                          title="Editar"
                          aria-label="Editar"
                          onClick={() => openEditModal(importer)}
                        >
                          <svg xmlns="http://www.w3.org/2000/svg" className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M11 5h2m-1 0v14m-7-7h14" />
                          </svg>
                        </button>
                        <button
                          className="inline-flex items-center justify-center p-2 rounded-full bg-red-50 hover:bg-red-100 text-red-700 transition-all focus:outline-none"
                          title="Eliminar"
                          aria-label="Eliminar"
                          onClick={() => openDeleteModal(importer)}
                        >
                          <svg xmlns="http://www.w3.org/2000/svg" className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                          </svg>
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>

          {/* Modal rendering outside table and empty state, always available */}
          {modalOpen && (
            <div className="fixed inset-0 bg-black bg-opacity-60 backdrop-blur-sm overflow-y-auto h-full w-full z-50 flex items-center justify-center p-4">
              <div className="relative mx-auto w-full max-w-xl bg-white rounded-2xl shadow-2xl transform transition-all duration-300 animate-in slide-in-from-bottom-4">
                {/* Modal Header */}
                <div className={`bg-gradient-to-r ${modalMode === 'delete' ? 'from-red-700 to-red-900 border-red-500' : 'from-blue-700 to-blue-900 border-blue-500'} rounded-t-2xl p-4 text-white border-b-2`}>
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-3">
                      <div className={`${modalMode === 'delete' ? 'bg-red-500 border-red-400' : 'bg-blue-500 border-blue-400'} bg-opacity-30 rounded-xl p-2 border border-opacity-30`}>
                        {modalMode === 'delete' ? (
                          <svg className="w-5 h-5" 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-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z" />
                          </svg>
                        ) : (
                          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
                          </svg>
                        )}
                      </div>
                      <div>
                        <h3 className="text-lg font-semibold tracking-wide">
                          {modalMode === 'delete' ? 'Eliminar Importador' : modalMode === 'edit' ? 'Editar Importador' : 'Ver Importador'}
                        </h3>
                        <p className={`${modalMode === 'delete' ? 'text-red-200' : 'text-blue-200'} text-xs font-medium`}>
                          {modalMode === 'delete' ? 'Esta acción no se puede deshacer.' : 'Sistema de Gestión de Importadores'}
                        </p>
                      </div>
                    </div>
                    <button
                      onClick={closeModal}
                      className={`${modalMode === 'delete' ? 'text-red-100 hover:text-white hover:bg-red-600' : 'text-blue-100 hover:text-white hover:bg-blue-600'} transition-colors p-2 hover:bg-opacity-50 rounded-lg border ${modalMode === 'delete' ? 'border-red-500' : 'border-blue-500'} border-opacity-30`}
                    >
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
                      </svg>
                    </button>
                  </div>
                </div>

                {/* Modal Content */}
                <div className="p-6">
                  {modalMode === 'delete' ? (
                    <div className="text-center">
                      <div className="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-red-100 mb-4">
                        <svg className="h-6 w-6 text-red-600" 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-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z" />
                        </svg>
                      </div>
                      <h3 className="text-lg font-medium text-gray-900 mb-2">¿Eliminar Importador?</h3>
                      <div className="mt-2 px-7 py-3">
                        <p className="text-sm text-gray-500 mb-4">
                          ¿Estás seguro que deseas eliminar el importador <strong>{modalData.nombre}</strong> (RFC: <strong>{modalData.rfc}</strong>)?
                        </p>
                        <div className="bg-gray-50 rounded-md p-3 mb-4">
                          <div className="flex items-center justify-center">
                            <div className="h-10 w-10 rounded-full bg-gray-300 flex items-center justify-center">
                              <svg className="h-6 w-6 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
                              </svg>
                            </div>
                            <div className="ml-3 text-left">
                              <p className="text-sm font-medium text-gray-900">{modalData.nombre}</p>
                              <p className="text-xs text-gray-500">RFC: {modalData.rfc}</p>
                            </div>
                          </div>
                        </div>
                        {errorMsg && <div className="text-red-500 mb-2 w-full">{errorMsg}</div>}
                      </div>
                      <div className="flex justify-center space-x-3 pt-4">
                        <button type="button" onClick={closeModal} disabled={modalLoading} className="px-6 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-semibold text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-slate-500 transition-all duration-200 disabled:opacity-50">Cancelar</button>
                        <button type="button" onClick={handleDeleteConfirm} disabled={modalLoading} className="px-6 py-2 border border-transparent rounded-md shadow-lg text-sm font-semibold text-white bg-gradient-to-r from-red-700 to-red-900 hover:from-red-800 hover:to-red-950 focus:ring-red-500 focus:outline-none focus:ring-2 focus:ring-offset-2 transition-all duration-200 flex items-center justify-center space-x-2 disabled:opacity-50 disabled:cursor-not-allowed">{modalLoading ? (<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>) : null}{modalLoading ? 'Eliminando...' : 'Eliminar Importador'}</button>
                      </div>
                    </div>
                  ) : (
                    <form onSubmit={async (e) => {
                      e.preventDefault();
                      setModalLoading(true);
                      setErrorMsg('');
                      try {
                        let res;
                        if (modalMode === 'edit') {
                          res = await fetchWithAuth(`${API_URL}/customs/importadores/${modalData.rfc}/`, {
                            method: 'PUT',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ rfc: modalData.rfc, nombre: modalData.nombre, organizacion: modalData.organizacion })
                          });
                          if (!res.ok) throw new Error('Error al actualizar importador');
                        } else if (modalMode === 'create') {
                          res = await fetchWithAuth(`${API_URL}/customs/importadores/`, {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ rfc: modalData.rfc, nombre: modalData.nombre, organizacion: modalData.organizacion })
                          });
                          if (!res.ok) throw new Error('Error al crear importador');
                        }
                        // Refrescar lista
                        const res2 = await fetchWithAuth(`${API_URL}/customs/importadores/`);
                        if (!res2.ok) throw new Error('Error al obtener importadores');
                        const data = await res2.json();
                        setImporters(Array.isArray(data) ? data : []);
                        closeModal();
                      } catch {
                        setErrorMsg(modalMode === 'create' ? 'Error al crear importador' : 'Error al actualizar importador');
                      } finally {
                        setModalLoading(false);
                      }
                    }} className="space-y-5">
                      <div>
                        <label className="block text-xs font-semibold text-slate-700 mb-1 text-left">RFC</label>
                        <input
                          name="rfc"
                          type="text"
                          value={modalData.rfc}
                          readOnly={modalMode !== 'create'}
                          className={`w-full px-3 py-2 border border-slate-300 rounded-md shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200 ${modalMode === 'create' ? 'bg-white' : 'bg-gray-100'} text-slate-900 placeholder-slate-400 text-sm`}
                          onChange={modalMode === 'create' ? handleModalChange : undefined}
                        />
                      </div>
                      <div>
                        <label className="block text-xs font-semibold text-slate-700 mb-1 text-left">Nombre</label>
                        <input
                          name="nombre"
                          type="text"
                          value={modalData.nombre}
                          onChange={modalMode !== 'view' ? handleModalChange : undefined}
                          readOnly={modalMode === 'view'}
                          className={`w-full px-3 py-2 border border-slate-300 rounded-md shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200 ${modalMode === 'view' ? 'bg-gray-100' : 'bg-white'} text-slate-900 placeholder-slate-400 text-sm`}
                        />
                      </div>
                      <div>
                        <label className="block text-xs font-semibold text-slate-700 mb-1 text-left">Organización</label>
                        <input
                          name="organizacion"
                          type="text"
                          value={modalData.organizacion}
                          onChange={modalMode !== 'view' ? handleModalChange : undefined}
                          readOnly={modalMode === 'view'}
                          className={`w-full px-3 py-2 border border-slate-300 rounded-md shadow-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200 ${modalMode === 'view' ? 'bg-gray-100' : 'bg-white'} text-slate-900 placeholder-slate-400 text-sm`}
                        />
                      </div>
                      {errorMsg && <div className="text-red-500 mt-2 text-sm text-center">{errorMsg}</div>}
                      <div className="flex flex-col sm:flex-row justify-end space-y-2 sm:space-y-0 sm:space-x-3 pt-4 border-t border-slate-200">
                        {modalMode !== 'view' && (
                          <button
                            type="button"
                            onClick={closeModal}
                            disabled={modalLoading}
                            className="w-full sm:w-auto px-6 py-2 border border-slate-300 rounded-md shadow-sm text-sm font-semibold text-slate-700 bg-white hover:bg-slate-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-slate-500 transition-all duration-200 disabled:opacity-50"
                          >
                            Cancelar
                          </button>
                        )}
                        {(modalMode === 'edit' || modalMode === 'create') && (
                          <button
                            type="submit"
                            disabled={modalLoading}
                            className={`w-full sm:w-auto px-6 py-2 border border-transparent rounded-md shadow-lg text-sm font-semibold text-white bg-gradient-to-r from-blue-700 to-blue-900 hover:from-blue-800 hover:to-blue-950 focus:ring-blue-500 focus:outline-none focus:ring-2 focus:ring-offset-2 transition-all duration-200 flex items-center justify-center space-x-2 disabled:opacity-50 disabled:cursor-not-allowed`}
                          >
                            {modalLoading && (
                              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                            )}
                            {modalLoading ? (modalMode === 'create' ? 'Creando...' : 'Actualizando...') : (modalMode === 'create' ? 'Crear' : 'Actualizar')}
                          </button>
                        )}
                      </div>
                    </form>
                  )}
                </div>
              </div>
            </div>
          )}
            </table>
          </div>

          {/* Paginación */}
          {totalImporters > 0 && (
            <div className="bg-white px-4 py-3 flex flex-col sm:flex-row items-center justify-between border-t border-gray-200">
              <div className="flex items-center mb-4 sm:mb-0">
                <span className="text-sm text-gray-700 mr-4">
                  Mostrando <span className="font-semibold">{startIndex + 1}</span> - <span className="font-semibold">{Math.min(endIndex, totalImporters)}</span> de <span className="font-semibold">{totalImporters}</span> importadores
                </span>
                <select
                  value={itemsPerPage}
                  onChange={e => handleItemsPerPageChange(Number(e.target.value))}
                  className="border border-gray-300 rounded-md px-3 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                >
                  <option value={10}>10 por página</option>
                  <option value={15}>15 por página</option>
                  <option value={20}>20 por página</option>
                </select>
              </div>
              {totalPages > 1 && (
                <div className="flex items-center space-x-2">
                  <button
                    onClick={e => handlePageChange(currentPage - 1, e)}
                    disabled={currentPage === 1}
                    className="relative inline-flex items-center px-3 py-2 rounded-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 19l-7-7 7-7" />
                    </svg>
                    Anterior
                  </button>
                  <div className="hidden sm:flex space-x-1">
                    {[...Array(totalPages)].map((_, index) => {
                      const page = index + 1;
                      const isCurrentPage = page === currentPage;
                      const isNearCurrentPage = Math.abs(page - currentPage) <= 2;
                      const isFirstOrLast = page === 1 || page === totalPages;
                      if (totalPages <= 7 || isNearCurrentPage || isFirstOrLast) {
                        return (
                          <button
                            key={page}
                            onClick={e => handlePageChange(page, e)}
                            className={`relative inline-flex items-center px-4 py-2 border text-sm font-medium rounded-md transition-colors ${isCurrentPage ? 'z-10 bg-blue-600 border-blue-600 text-white' : 'bg-white border-gray-300 text-gray-500 hover:bg-gray-50'}`}
                          >
                            {page}
                          </button>
                        );
                      } else if (page === currentPage - 3 || page === currentPage + 3) {
                        return (
                          <span key={page} className="relative inline-flex items-center px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-700">...</span>
                        );
                      }
                      return null;
                    })}
                  </div>
                  <div className="sm:hidden flex items-center space-x-2">
                    <span className="text-sm text-gray-700">Página {currentPage} de {totalPages}</span>
                  </div>
                  <button
                    onClick={e => handlePageChange(currentPage + 1, e)}
                    disabled={currentPage === totalPages}
                    className="relative inline-flex items-center px-3 py-2 rounded-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    Siguiente
                    <svg className="w-4 h-4 ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5l7 7-7 7" />
                    </svg>
                  </button>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Estado vacío */}
        {currentImporters.length === 0 && !loading && (
          <div className="bg-white rounded-xl shadow-lg border border-gray-200 p-6 sm:p-12">
            <div className="text-center">
              <div className="mx-auto h-20 w-20 sm:h-24 sm:w-24 bg-gradient-to-br from-gray-100 to-gray-200 rounded-full flex items-center justify-center mb-6">
                <svg className="h-10 w-10 sm:h-12 sm:w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" />
                </svg>
              </div>
              <h3 className="text-base sm:text-lg font-semibold text-gray-900 mb-2">No se encontraron importadores</h3>
              <p className="text-gray-500 mb-6">{searchTerm ? 'Intenta con otros términos de búsqueda.' : 'Comienza agregando un nuevo importador.'}</p>
              {!searchTerm && (
                <button
                  className="inline-flex items-center px-4 py-2 border border-transparent rounded-lg shadow-sm text-xs sm:text-sm font-medium text-white bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-all duration-200 transform hover:scale-105"
                  onClick={() => {
                    setModalMode('create');
                    setModalData({ rfc: '', nombre: '', organizacion: '' });
                    setErrorMsg('');
                    setModalOpen(true);
                  }}
                >
                  <svg className="-ml-1 mr-2 h-4 w-4 sm:h-5 sm:w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                  </svg>
                  Agregar primer importador
                </button>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
