// Sistema de Expedientes de Departamentos - Reports Section
// Compatible con estructura DiegoBanuelosS/esperiency

// Función para obtener rol del usuario
function getUserRole() {
  const jwt = getJWTFromStorage?.() || localStorage.getItem('jwt') || sessionStorage.getItem('jwt');
  if (!jwt) return 'user';
  try {
    const payload = JSON.parse(atob(jwt.split('.')[1]));
    return payload?.organizationRole || payload?.role || 'user';
  } catch {
    return 'user';
  }
}
// Data de expedientes de departamentos
// Nota: Array vacío - agrega tus departamentos reales desde la sección de Tenants/Departamentos
const DEPARTMENTS_DATA = [];

// Search bar para filtrar expedientes
function SearchBar({ searchTerm, setSearchTerm }) {
  return (
    <div className="mb-6">
      <div className="relative">
        <div className="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
          <svg className="h-5 w-5 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
        </div>
        <input
          type="text"
          placeholder="Buscar departamento o inquilino..."
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          className="search-bar-black"
        />
      </div>
    </div>
  );
}

// Modal para agregar nuevo expediente
function AddExpedienteModal({ isOpen, onClose, departmentData, onAdd }) {
  const [type, setType] = React.useState('');
  const [description, setDescription] = React.useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!type || !description) return;
    
    onAdd({
      type,
      description,
      date: new Date().toISOString().split('T')[0]
    });
    
    setType('');
    setDescription('');
    onClose();
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50">
      <div className="bg-gray-900 rounded-xl p-6 w-full max-w-md mx-4 border border-gray-700">
        <div className="flex justify-between items-center mb-6">
          <h3 className="text-xl font-bold text-white">
            Nuevo Expediente
          </h3>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-white transition-colors p-1"
          >
            <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 className="mb-4 p-3 bg-gray-800 rounded-lg">
          <p className="text-gray-300 text-sm">
            <span className="font-semibold text-white">Departamento:</span> {departmentData?.number}
          </p>
          <p className="text-gray-300 text-sm">
            <span className="font-semibold text-white">Inquilino:</span> {departmentData?.tenant}
          </p>
        </div>
        
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-white font-medium mb-2">Tipo de Expediente</label>
            <select
              className="input-main"
              value={type}
              onChange={(e) => setType(e.target.value)}
              required
            >
              <option value="">Seleccionar tipo...</option>
              <option value="Contrato">📄 Contrato</option>
              <option value="Pago">💰 Pago</option>
              <option value="Mantenimiento">🔧 Mantenimiento</option>
              <option value="Queja">⚠️ Queja</option>
              <option value="Otro">📋 Otro</option>
            </select>
          </div>
          
          <div>
            <label className="block text-white font-medium mb-2">Descripción</label>
            <textarea
              className="input-main resize-none"
              rows={4}
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Descripción detallada del expediente..."
              required
            />
          </div>
          
          <div className="flex space-x-3 pt-4">
            <button
              type="button"
              onClick={onClose}
              className="flex-1 py-2 px-4 bg-gray-700 text-white rounded-lg hover:bg-gray-600 transition-colors"
            >
              Cancelar
            </button>
            <button
              type="submit"
              className="btn-main flex-1 py-2"
            >
              Agregar
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

// Lista de expedientes por departamento  
function ExpedientesList({ departments, onSelectDepartment, selectedDepartment, onAddExpediente }) {
  return (
    <div className="space-y-4">
      {departments.map((dept) => (
        <div key={dept.id} className="report-card p-6">
          {/* Header del departamento */}
          <div 
            className={`flex items-center justify-between p-4 rounded-lg cursor-pointer transition-all ${
              selectedDepartment?.id === dept.id 
                ? 'bg-black/40 border-2 border-gray-500' 
                : 'hover:bg-gray-800/30'
            }`}
            onClick={() => onSelectDepartment(dept)}
          >
            <div className="flex items-center space-x-4">
              <div className="w-12 h-12 bg-black border-2 border-gray-600 rounded-xl flex items-center justify-center">
                <svg className="w-6 h-6 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>
                <h3 className="text-xl font-bold text-white">Departamento {dept.number}</h3>
                <p className="text-gray-300 font-medium">{dept.tenant}</p>
                <span className={`text-sm px-2 py-1 rounded-full ${
                  dept.status === 'Ocupado' ? 'bg-green-500/20 text-green-400' : 'bg-orange-500/20 text-orange-400'
                }`}>
                  {dept.status}
                </span>
              </div>
            </div>
            
            <div className="flex items-center space-x-4">
              <div className="text-center">
                <div className="text-gray-400 text-sm">Expedientes</div>
                <div className="text-white font-bold text-xl">{dept.expedientes.length}</div>
              </div>
              <svg className="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
              </svg>
            </div>
          </div>

          {/* Lista de expedientes y botón agregar */}
          {selectedDepartment?.id === dept.id && (
            <div className="mt-4">
              {/* Botón para agregar expediente */}
              <div className="mb-4">
                <button
                  onClick={() => onAddExpediente(dept)}
                  className="btn-main px-4 py-2 flex items-center space-x-2 w-full sm:w-auto"
                >
                  <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>
                  <span>Agregar Expediente</span>
                </button>
              </div>

              {/* Lista de expedientes */}
              <div className="space-y-3 ml-4 pl-4 border-l-2 border-gray-600">
                {dept.expedientes.map((exp) => (
                  <div key={exp.id} className="flex items-center justify-between bg-gray-800/40 rounded-lg p-4">
                    <div className="flex items-center space-x-3">
                      <div className={`w-3 h-3 rounded-full ${
                        exp.type === 'Contrato' ? 'bg-blue-400' :
                        exp.type === 'Pago' ? 'bg-green-400' :
                        exp.type === 'Mantenimiento' ? 'bg-yellow-400' :
                        exp.type === 'Queja' ? 'bg-red-400' : 'bg-gray-400'
                      }`}></div>
                      <div>
                        <p className="text-white font-medium">{exp.type}</p>
                        <p className="text-gray-400 text-sm">{exp.description}</p>
                      </div>
                    </div>
                    <div className="text-right">
                      <p className="text-gray-400 text-sm">
                        {new Date(exp.date).toLocaleDateString('es-CO')}
                      </p>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      ))}
    </div>
  );
}

// Componente para agregar expediente (página completa)
function AddExpedientePage({ selectedDepartment, onAdd, onCancel }) {
  const [type, setType] = React.useState('');
  const [description, setDescription] = React.useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!type || !description) return;
    
    onAdd({
      type,
      description,
      date: new Date().toISOString().split('T')[0]
    });
    
    setType('');
    setDescription('');
  };

  return (
    <div className="min-h-screen bg-black pt-8 pb-16">
      <div className="max-w-3xl mx-auto px-6">
        {/* Header */}
        <div className="mb-8">
          <button
            onClick={onCancel}
            className="flex items-center space-x-2 text-gray-400 hover:text-white transition-colors mb-6"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
            </svg>
            <span>Volver a Reportes</span>
          </button>
          
          <h1 className="report-title mb-4">Nuevo Expediente</h1>
          <p className="text-gray-400 text-lg">
            Agregar nuevo expediente al departamento
          </p>
        </div>

        {/* Info del departamento */}
        <div className="report-card p-6 mb-6">
          <div className="flex items-center space-x-4">
            <div className="w-16 h-16 bg-black border-2 border-gray-600 rounded-xl flex items-center justify-center">
              <svg className="w-8 h-8 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>
              <h2 className="text-2xl font-bold text-white">Departamento {selectedDepartment?.number}</h2>
              <p className="text-gray-300 text-lg">{selectedDepartment?.tenant}</p>
              <span className={`text-sm px-3 py-1 rounded-full inline-block mt-2 ${
                selectedDepartment?.status === 'Ocupado' ? 'bg-green-500/20 text-green-400' : 'bg-orange-500/20 text-orange-400'
              }`}>
                {selectedDepartment?.status}
              </span>
            </div>
          </div>
        </div>

        {/* Formulario */}
        <form onSubmit={handleSubmit} className="report-card p-8">
          <div className="space-y-6">
            <div>
              <label className="label-main">Tipo de Expediente</label>
              <select
                className="input-main"
                value={type}
                onChange={(e) => setType(e.target.value)}
                required
              >
                <option value="">Seleccionar tipo...</option>
                <option value="Contrato">📄 Contrato</option>
                <option value="Pago">💰 Pago</option>
                <option value="Mantenimiento">🔧 Mantenimiento</option>
                <option value="Queja">⚠️ Queja</option>
                <option value="Otro">📋 Otro</option>
              </select>
            </div>
            
            <div>
              <label className="label-main">Descripción</label>
              <textarea
                className="input-main resize-none"
                rows={6}
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                placeholder="Descripción detallada del expediente..."
                required
              />
            </div>
            
            <div className="flex space-x-4 pt-6">
              <button
                type="button"
                onClick={onCancel}
                className="btn-main flex-1 py-3 px-6 text-lg"
              >
                Cancelar
              </button>
              <button
                type="submit"
                className="btn-main flex-1 py-3 px-6 text-lg"
              >
                Agregar Expediente
              </button>
            </div>
          </div>
        </form>
      </div>
    </div>
  );
}

// Componente principal de Reports
function ReportsSection() {
    const [departments, setDepartments] = React.useState(DEPARTMENTS_DATA);
  const [searchTerm, setSearchTerm] = React.useState('');
  const [selectedDepartment, setSelectedDepartment] = React.useState(null);
  const [isAddingExpediente, setIsAddingExpediente] = React.useState(false);
  const [departmentToAddExpediente, setDepartmentToAddExpediente] = React.useState(null);
  const [message, setMessage] = React.useState('');

  // Filtrar departamentos por búsqueda
  const filteredDepartments = departments.filter(dept =>
    dept.number.toLowerCase().includes(searchTerm.toLowerCase()) ||
    (dept.tenant && dept.tenant.toLowerCase().includes(searchTerm.toLowerCase()))
  );

  const handleSelectDepartment = (dept) => {
    setSelectedDepartment(dept);
  };

  const handleAddExpediente = (dept) => {
    setDepartmentToAddExpediente(dept);
    setIsAddingExpediente(true);
  };

  const handleCancelAdd = () => {
    setIsAddingExpediente(false);
    setDepartmentToAddExpediente(null);
  };

  const handleAddExpedienteSubmit = (expedienteData) => {
    const newExpediente = {
      id: Date.now(),
      ...expedienteData
    };

    setDepartments(prevDepts =>
      prevDepts.map(dept =>
        dept.id === departmentToAddExpediente.id
          ? { ...dept, expedientes: [...dept.expedientes, newExpediente] }
          : dept
      )
    );

    // Actualizar el departamento seleccionado si es el mismo
    if (selectedDepartment?.id === departmentToAddExpediente.id) {
      setSelectedDepartment(prev => ({
        ...prev,
        expedientes: [...prev.expedientes, newExpediente]
      }));
    }

    setMessage('¡Expediente agregado correctamente!');
    setTimeout(() => setMessage(''), 3000);
    
    // Volver a la vista de reportes
    setIsAddingExpediente(false);
    setDepartmentToAddExpediente(null);
  };

  // Si está agregando expediente, mostrar página de agregar
  if (isAddingExpediente && departmentToAddExpediente) {
    return (
      <AddExpedientePage
        selectedDepartment={departmentToAddExpediente}
        onAdd={handleAddExpedienteSubmit}
        onCancel={handleCancelAdd}
      />
    );
  }

  return (
    <div className="min-h-screen bg-black pt-8 pb-16">
      <div className="max-w-7xl mx-auto px-6">
        {/* Header */}
        <div className="text-center mb-12">
          <div className="inline-flex items-center justify-center w-20 h-20 bg-black border border-gray-700 rounded-full mb-6">
            <svg className="w-10 h-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>
          <h1 className="report-title mb-4">
            Expedientes de Departamentos
          </h1>
          <p className="text-xl text-gray-400 max-w-2xl mx-auto leading-relaxed">
            Gestión completa de expedientes y documentación por departamento
          </p>
        </div>

        {message && (
          <div className="success-message max-w-2xl mx-auto mb-8">
            <div className="flex items-center justify-center space-x-3">
              <svg className="w-6 h-6 text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
              </svg>
              <span>{message}</span>
            </div>
          </div>
        )}

        {/* Search bar */}
        <SearchBar searchTerm={searchTerm} setSearchTerm={setSearchTerm} />

        {/* Lista de expedientes */}
        <ExpedientesList
          departments={filteredDepartments}
          onSelectDepartment={handleSelectDepartment}
          selectedDepartment={selectedDepartment}
          onAddExpediente={handleAddExpediente}
        />
      </div>
    </div>
  );
}

// Exportar globalmente para que lo use index-babel.jsx
window.ReportsSystem = ReportsSection;
