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 PharmacyProductLink() {
  const [pharmacies, setPharmacies] = useState([]);
  const [productSearch, setProductSearch] = useState('');
  const [productResults, setProductResults] = useState([]);
  const [selectedPharmacy, setSelectedPharmacy] = useState(null);
  const [selectedProduct, setSelectedProduct] = useState(null);
  const [pharmacyProducts, setPharmacyProducts] = 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) {
      fetchPharmacyProducts(selectedPharmacy.id);
    }
  }, [selectedPharmacy]);

  // Buscar productos en la API mientras el usuario escribe
  useEffect(() => {
    const q = productSearch.trim();
    if (q.length < 2) {
      setProductResults([]);
      setSearching(false);
      return;
    }

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

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

  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 fetchPharmacyProducts = async (pharmacyId) => {
    setLoading(true);
    try {
      const response = await fetch(`/api/admin/pharmacies/${pharmacyId}/products`, {
        credentials: 'include',
      });
      const data = await response.json();
      setPharmacyProducts(data);
    } catch (error) {
      console.error('Error fetching pharmacy products:', error);
    } finally {
      setLoading(false);
    }
  };

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

    try {
      // Build identifier: source:id (e.g., openfoodfacts:9421025231209)
      const identifier = selectedProduct._id 
        ? `${selectedProduct.source || 'openfoodfacts'}:${selectedProduct._id}`
        : `${selectedProduct.source || 'openfoodfacts'}:${selectedProduct.id}`;

      const payload = {
        pharmacy_id: parseInt(formData.pharmacy_id),
        product_source: selectedProduct.source || 'openfoodfacts',
        product_off_id: selectedProduct._id || selectedProduct.id,
        product_name: selectedProduct.product_name || selectedProduct.name,
        price: formData.price ? parseFloat(formData.price) : null,
        stock: formData.stock ? parseInt(formData.stock) : 0
      };

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

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

      resetForm();
      if (selectedPharmacy) {
        fetchPharmacyProducts(selectedPharmacy.id);
      }
      alert('¡Producto vinculado a la farmacia correctamente!');
    } catch (error) {
      console.error('Error linking product:', error);
      alert('Error al vincular producto a farmacia');
    }
  };

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

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

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

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

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

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

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

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

  const selectProduct = (product) => {
    setSelectedProduct(product);
    setProductSearch(product.product_name || product.name);
    setProductResults([]);
  };

  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);
  };

  const getSourceBadge = (source) => {
    if (source === 'cima') {
      return <span className="source-badge source-badge--cima">CIMA</span>;
    }
    return <span className="source-badge source-badge--off">OFF</span>;
  };

  return (
    <div className="admin-section">
      <h2>Vincular Producto 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 Producto (Open Food Facts) *</label>
          <input
            type="text"
            value={productSearch}
            onChange={(e) => {
              setProductSearch(e.target.value);
              setSelectedProduct(null);
            }}
            placeholder="Escribe para buscar productos..."
            required
          />
          {searching && <p className="loading-text">Buscando...</p>}
          
          {productResults.length > 0 && !selectedProduct && (
            <div className="medicine-search-results">
              {productResults.slice(0, 10).map((product) => (
                <div 
                  key={product._id || product.id} 
                  className="search-result-item"
                  onClick={() => selectProduct(product)}
                >
                  <strong>{product.product_name || product.name}</strong>
                  {product.brands && <span> - {product.brands}</span>}
                  {product.quantity && <span> ({product.quantity})</span>}
                </div>
              ))}
            </div>
          )}

          {selectedProduct && (
            <div className="selected-medicine-info">
              <p>✅ Selected: <strong>{selectedProduct.product_name || selectedProduct.name}</strong></p>
              <p className="medicine-details">
                {selectedProduct.brands && `Marca: ${selectedProduct.brands} • `}
                {selectedProduct.quantity && `Cantidad: ${selectedProduct.quantity} • `}
                {getSourceBadge(selectedProduct.source || 'openfoodfacts')}
                {' '}
                {selectedProduct._id || selectedProduct.id}
              </p>
              <button 
                type="button" 
                className="btn-small" 
                onClick={() => {
                  setSelectedProduct(null);
                  setProductSearch('');
                }}
              >
                Cambiar producto
              </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., 3.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., 100"
            />
          </div>
        </div>

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

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

export default PharmacyProductLink;
