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

const MAX_PHARMACY_RESULTS = 25;

function normalize(s) {
  return (s || '').toString().toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '');
}

function PharmacyMedicineLink() {
  const [pharmacies, setPharmacies] = useState([]);
  const [medicineSearch, setMedicineSearch] = useState('');
  const [medicineResults, setMedicineResults] = useState([]);
  const [selectedPharmacy, setSelectedPharmacy] = useState(null);
  const [selectedMedicine, setSelectedMedicine] = useState(null);
  const [pharmacyMedicines, setPharmacyMedicines] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searching, setSearching] = useState(false);
  const [pharmacyQuery, setPharmacyQuery] = useState('');
  const [pharmacyDropdownOpen, setPharmacyDropdownOpen] = useState(false);
  const pharmacyInputRef = useRef(null);
  const [formData, setFormData] = useState({
    pharmacy_id: '',
    price: '',
    stock: ''
  });

  const filteredPharmacies = useMemo(() => {
    const q = normalize(pharmacyQuery).trim();
    if (!q) return pharmacies.slice(0, MAX_PHARMACY_RESULTS);
    const tokens = q.split(/\s+/).filter(Boolean);
    return pharmacies
      .filter(p => {
        const hay = `${normalize(p.name)} ${normalize(p.address)}`;
        return tokens.every(tok => hay.includes(tok));
      })
      .slice(0, MAX_PHARMACY_RESULTS);
  }, [pharmacies, pharmacyQuery]);

  useEffect(() => {
    fetchPharmacies();
  }, []);

  useEffect(() => {
    if (selectedPharmacy) {
      fetchPharmacyMedicines(selectedPharmacy.id);
    }
  }, [selectedPharmacy]);

  // Buscar medicamentos en la API de CIMA mientras el usuario escribe
  useEffect(() => {
    const q = medicineSearch.trim();
    if (q.length < 2) {
      setMedicineResults([]);
      setSearching(false);
      return;
    }

    const controller = new AbortController();
    const timeoutId = setTimeout(async () => {
      setSearching(true);
      try {
        const response = await fetch(`/api/medicines/search?q=${encodeURIComponent(q)}`, {
          credentials: 'include',
          signal: controller.signal,
        });
        const data = await response.json();
        setMedicineResults(Array.isArray(data) ? data : []);
      } catch (error) {
        if (error.name === 'AbortError') return;
        console.error('Error searching medicines:', error);
      } finally {
        if (!controller.signal.aborted) setSearching(false);
      }
    }, 500);

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

  const fetchPharmacies = async () => {
    try {
      const response = await fetch('/api/pharmacies', {
        credentials: 'include',
      });
      const data = await response.json();
      setPharmacies(data);
    } catch (error) {
      console.error('Error fetching pharmacies:', error);
    }
  };

  const fetchPharmacyMedicines = async (pharmacyId) => {
    setLoading(true);
    try {
      const response = await fetch(`/api/admin/pharmacies/${pharmacyId}/medicines`, {
        credentials: 'include',
      });
      const data = await response.json();
      setPharmacyMedicines(data);
    } catch (error) {
      console.error('Error fetching pharmacy medicines:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    if (!selectedMedicine) {
      alert('Por favor, selecciona un medicamento primero');
      return;
    }

    try {
      const payload = {
        pharmacy_id: parseInt(formData.pharmacy_id),
        medicine_nregistro: selectedMedicine.nregistro,
        medicine_name: selectedMedicine.name,
        price: formData.price ? parseFloat(formData.price) : null,
        stock: formData.stock ? parseInt(formData.stock) : 0
      };

      const response = await fetch('/api/admin/pharmacy-medicines', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify(payload)
      });

      if (!response.ok) throw new Error('Error al vincular medicamento a farmacia');

      resetForm();
      if (selectedPharmacy) {
        fetchPharmacyMedicines(selectedPharmacy.id);
      }
      alert('¡Medicamento vinculado a la farmacia correctamente!');
    } catch (error) {
      console.error('Error linking medicine:', error);
      alert('Error al vincular medicamento a farmacia');
    }
  };

  const handleUpdate = async (id, price, stock) => {
    try {
      const response = await fetch(`/api/admin/pharmacy-medicines/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ price, stock })
      });

      if (!response.ok) throw new Error('Error al actualizar');

      fetchPharmacyMedicines(selectedPharmacy.id);
      alert('¡Actualizado correctamente!');
    } catch (error) {
      console.error('Error updating:', error);
      alert('Error al actualizar');
    }
  };

  const handleDelete = async (id) => {
    if (!confirm('¿Eliminar este medicamento de la farmacia?')) return;

    try {
      const response = await fetch(`/api/admin/pharmacy-medicines/${id}`, {
        method: 'DELETE',
        credentials: 'include'
      });

      if (!response.ok) throw new Error('Error al eliminar');

      fetchPharmacyMedicines(selectedPharmacy.id);
      alert('¡Medicamento eliminado de la farmacia!');
    } catch (error) {
      console.error('Error deleting:', error);
      alert('Error al eliminar medicamento');
    }
  };

  const resetForm = () => {
    setFormData({
      pharmacy_id: selectedPharmacy ? selectedPharmacy.id.toString() : '',
      price: '',
      stock: ''
    });
    setSelectedMedicine(null);
    setMedicineSearch('');
    setMedicineResults([]);
  };

  const selectMedicine = (medicine) => {
    setSelectedMedicine(medicine);
    setMedicineSearch(medicine.name);
    setMedicineResults([]);
  };

  const pickPharmacy = (pharmacy) => {
    setSelectedPharmacy(pharmacy);
    setFormData(prev => ({ ...prev, pharmacy_id: pharmacy.id.toString() }));
    setPharmacyQuery(`${pharmacy.name} — ${pharmacy.address}`);
    setPharmacyDropdownOpen(false);
  };

  const clearPharmacy = () => {
    setSelectedPharmacy(null);
    setFormData(prev => ({ ...prev, pharmacy_id: '' }));
    setPharmacyQuery('');
    setPharmacyDropdownOpen(true);
    setTimeout(() => pharmacyInputRef.current?.focus(), 0);
  };

  return (
    <div className="admin-section">
      <h2>Vincular Medicamento a Farmacia</h2>

      <form className="admin-form" onSubmit={handleSubmit}>
        <div className="form-group">
          <label>Farmacia *</label>
          <input
            ref={pharmacyInputRef}
            type="text"
            value={pharmacyQuery}
            onChange={(e) => {
              setPharmacyQuery(e.target.value);
              if (selectedPharmacy) {
                setSelectedPharmacy(null);
                setFormData(prev => ({ ...prev, pharmacy_id: '' }));
              }
              setPharmacyDropdownOpen(true);
            }}
            onFocus={() => setPharmacyDropdownOpen(true)}
            onBlur={() => setTimeout(() => setPharmacyDropdownOpen(false), 150)}
            placeholder={pharmacies.length ? `Buscar entre ${pharmacies.length} farmacias por nombre o dirección…` : 'Cargando farmacias…'}
            autoComplete="off"
            required={!selectedPharmacy}
          />
          {!selectedPharmacy && pharmacyDropdownOpen && (
            <div className="medicine-search-results">
              {filteredPharmacies.length === 0 ? (
                <div className="search-result-item search-result-item--empty">
                  <span>No hay farmacias que coincidan con "{pharmacyQuery}"</span>
                </div>
              ) : (
                filteredPharmacies.map((pharmacy) => (
                  <div
                    key={pharmacy.id}
                    className="search-result-item"
                    onMouseDown={(e) => { e.preventDefault(); pickPharmacy(pharmacy); }}
                  >
                    <strong>{pharmacy.name}</strong>
                    <span>{pharmacy.address}</span>
                  </div>
                ))
              )}
            </div>
          )}
          {selectedPharmacy && (
            <div className="selected-medicine-info">
              <p>✅ Selected: <strong>{selectedPharmacy.name}</strong></p>
              <p className="medicine-details">{selectedPharmacy.address}</p>
              <button type="button" className="btn-small" onClick={clearPharmacy}>
                Cambiar farmacia
              </button>
            </div>
          )}
        </div>

        <div className="form-group">
          <label>Buscar Medicamento (API CIMA) *</label>
          <input
            type="text"
            value={medicineSearch}
            onChange={(e) => {
              setMedicineSearch(e.target.value);
              setSelectedMedicine(null);
            }}
            placeholder="Escribe para buscar medicamentos en CIMA..."
            required
          />
          {searching && <p className="loading-text">Buscando...</p>}
          
          {medicineResults.length > 0 && !selectedMedicine && (
            <div className="medicine-search-results">
              {medicineResults.slice(0, 10).map((medicine) => (
                <div 
                  key={medicine.nregistro} 
                  className="search-result-item"
                  onClick={() => selectMedicine(medicine)}
                >
                  <strong>{medicine.name}</strong>
                  {medicine.active_ingredient && <span> - {medicine.active_ingredient}</span>}
                  {medicine.dosage && <span> ({medicine.dosage})</span>}
                </div>
              ))}
            </div>
          )}

          {selectedMedicine && (
            <div className="selected-medicine-info">
              <p>✅ Selected: <strong>{selectedMedicine.name}</strong></p>
              <p className="medicine-details">
                {selectedMedicine.active_ingredient && `Principio activo: ${selectedMedicine.active_ingredient} • `}
                {selectedMedicine.dosage && `Dosis: ${selectedMedicine.dosage} • `}
                Nº Registro: {selectedMedicine.nregistro}
              </p>
              <button 
                type="button" 
                className="btn-small" 
                onClick={() => {
                  setSelectedMedicine(null);
                  setMedicineSearch('');
                }}
              >
                Cambiar medicamento
              </button>
            </div>
          )}
        </div>

        <div className="form-row">
          <div className="form-group">
            <label>Precio (€)</label>
            <input
              type="number"
              step="0.01"
              value={formData.price}
              onChange={(e) => setFormData({ ...formData, price: e.target.value })}
              placeholder="e.g., 12.50"
            />
          </div>

          <div className="form-group">
            <label>Stock</label>
            <input
              type="number"
              value={formData.stock}
              onChange={(e) => setFormData({ ...formData, stock: e.target.value })}
              placeholder="e.g., 50"
            />
          </div>
        </div>

        <div className="form-actions">
          <button type="submit" className="btn-primary">
            Vincular Medicamento
          </button>
          <button type="button" className="btn-secondary" onClick={resetForm}>
            Reiniciar
          </button>
        </div>
      </form>

      {selectedPharmacy && (
        <div className="pharmacy-medicines-section">
          <h3>Medicamentos en {selectedPharmacy.name}</h3>
          {loading ? (
            <div className="loading">Cargando...</div>
          ) : pharmacyMedicines.length === 0 ? (
            <p className="empty-state">Aún no hay medicamentos vinculados a esta farmacia.</p>
          ) : (
            <div className="admin-list">
              {pharmacyMedicines.map((pm) => (
                <div key={pm.id} className="admin-item">
                  <div className="item-content">
                    <h4>{pm.medicine_name}</h4>
                    <p>
                      <strong>Precio:</strong> {pm.price ? `€${parseFloat(pm.price).toFixed(2)}` : 'No definido'} • 
                      <strong> Stock:</strong> {pm.stock || 0}
                    </p>
                  </div>
                  <div className="item-actions">
                    <button 
                      className="btn-edit"
                      onClick={() => {
                        const newPrice = prompt('Introduce nuevo precio:', pm.price || '');
                        const newStock = prompt('Introduce nuevo stock:', pm.stock || '0');
                        if (newPrice !== null && newStock !== null) {
                          handleUpdate(pm.id, newPrice ? parseFloat(newPrice) : null, parseInt(newStock) || 0);
                        }
                      }}
                    >
                      Actualizar
                    </button>
                    <button className="btn-delete" onClick={() => handleDelete(pm.id)}>
                      Eliminar
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

export default PharmacyMedicineLink;

