import React, { useState, useEffect } from 'react';
import './AdminComponents.css';

const SEARCH_DEBOUNCE_MS = 400;

function MedicineManagement() {
  const [searchQuery, setSearchQuery] = useState('');
  const [medicines, setMedicines] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const q = searchQuery.trim();
    if (q.length < 2) {
      setMedicines([]);
      setLoading(false);
      return;
    }

    const controller = new AbortController();
    const timeoutId = setTimeout(async () => {
      setLoading(true);
      try {
        const response = await fetch(
          `/api/medicines/search?q=${encodeURIComponent(q)}`,
          { credentials: 'include', signal: controller.signal }
        );
        const data = await response.json();
        setMedicines(Array.isArray(data) ? data : []);
      } catch (error) {
        if (error.name === 'AbortError') return;
        console.error('Error searching medicines:', error);
        alert('Error al buscar medicamentos en la API CIMA');
      } finally {
        if (!controller.signal.aborted) setLoading(false);
      }
    }, SEARCH_DEBOUNCE_MS);

    return () => {
      clearTimeout(timeoutId);
      controller.abort();
    };
  }, [searchQuery]);

  return (
    <div className="admin-section">
      <div className="section-header">
        <h2>Buscar Medicamentos (API CIMA)</h2>
      </div>

      <div className="info-box">
        <p>ℹ️ Los medicamentos ahora se obtienen directamente de la <strong>API de CIMA</strong> (Agencia Española de Medicamentos y Productos Sanitarios).</p>
        <p>Busca medicamentos para vincularlos a farmacias en la pestaña "Link Medicine".</p>
      </div>

      <div className="admin-form">
        <div className="form-group">
          <label>Buscar medicamentos</label>
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Escribe el nombre de un medicamento..."
          />
        </div>
      </div>

      {loading && <div className="loading">Buscando en API CIMA...</div>}

      {!loading && medicines.length > 0 && (
        <div className="admin-list">
          <p className="info-text">Se encontraron {medicines.length} medicamentos</p>
          {medicines.map((medicine) => (
            <div key={medicine.nregistro} className="admin-item">
              <div className="item-content">
                <h4>{medicine.name}</h4>
                {medicine.active_ingredient && (
                  <p><strong>Principio Activo:</strong> {medicine.active_ingredient}</p>
                )}
                <p>
                  {medicine.dosage && <span><strong>Dosis:</strong> {medicine.dosage}</span>}
                  {medicine.dosage && medicine.form && ' • '}
                  {medicine.form && <span><strong>Forma:</strong> {medicine.form}</span>}
                </p>
                <p className="medicine-meta">
                  <strong>Laboratorio:</strong> {medicine.laboratory} • 
                  <strong> Nº Registro:</strong> {medicine.nregistro} • 
                  {medicine.generic ? ' Genérico' : ' Marca'}
                </p>
              </div>
            </div>
          ))}
        </div>
      )}

      {!loading && searchQuery.trim().length >= 2 && medicines.length === 0 && (
        <p className="empty-state">No se encontraron medicamentos con ese nombre.</p>
      )}
    </div>
  );
}

export default MedicineManagement;
