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

function SavedNotifications({ onClose, onNotificationChange }) {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [items, setItems] = useState([]);
  const [busyId, setBusyId] = useState(null);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const res = await fetch('/api/notifications/mine', { credentials: 'include' });
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        const data = await res.json();
        if (cancelled) return;
        const merged = [
          ...(data.pharmacy || []),
          ...(data.global || []),
        ].sort((a, b) => (b.created_at || '').localeCompare(a.created_at || ''));
        setItems(merged);
      } catch (err) {
        if (!cancelled) setError(err.message || 'No se pudieron cargar las notificaciones guardadas');
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, []);

  async function handleDelete(item) {
    const key = `${item.scope}:${item.id}`;
    setBusyId(key);
    try {
      const res = await fetch('/api/notifications/mine', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ scope: item.scope, id: item.id }),
      });
      if (!res.ok && res.status !== 204) throw new Error(`HTTP ${res.status}`);
      setItems(prev => prev.filter(i => !(i.scope === item.scope && i.id === item.id)));
      onNotificationChange?.();
    } catch (err) {
      setError(err.message || 'No se pudo eliminar la notificación');
    } finally {
      setBusyId(null);
    }
  }

  return (
    <div className="saved-notifications-backdrop" onClick={onClose}>
      <div className="saved-notifications-modal" onClick={e => e.stopPropagation()}>
        <div className="saved-notifications-header">
          <h2>🔔 Notificaciones Guardadas</h2>
          <button className="saved-notifications-close" onClick={onClose} aria-label="Cerrar">×</button>
        </div>
        <div className="saved-notifications-body">
          {loading && <p className="saved-notifications-status">Cargando…</p>}
          {!loading && error && <p className="saved-notifications-error">{error}</p>}
          {!loading && !error && items.length === 0 && (
            <p className="saved-notifications-empty">
              Aún no hay notificaciones guardadas. Toca la campana 🔕 en una farmacia sin stock para recibir notificaciones cuando se reponga.
            </p>
          )}
          {!loading && !error && items.length > 0 && (
            <ul className="saved-notifications-list">
              {items.map(item => {
                const key = `${item.scope}:${item.id}`;
                return (
                  <li key={key} className="saved-notifications-item">
                    <div className="saved-notifications-item-main">
                      <div className="saved-notifications-item-name">
                        {item.medicine_name || item.medicine_nregistro}
                      </div>
                      <div className="saved-notifications-item-meta">
                        {item.scope === 'pharmacy' ? (
                          <>
                            <span className="saved-notifications-chip saved-notifications-chip--pharmacy">
                              🏥 {item.pharmacy_name || `Farmacia #${item.pharmacy_id}`}
                            </span>
                            {item.pharmacy_address && (
                              <span className="saved-notifications-address">{item.pharmacy_address}</span>
                            )}
                          </>
                        ) : (
                          <span className="saved-notifications-chip">
                            Cualquier farmacia
                          </span>
                        )}
                      </div>
                    </div>
                    <button
                      type="button"
                      className="saved-notifications-remove"
                      onClick={() => handleDelete(item)}
                      disabled={busyId === key}
                      aria-label="Eliminar notificación"
                    >
                      {busyId === key ? '…' : 'Eliminar'}
                    </button>
                  </li>
                );
              })}
            </ul>
          )}
        </div>
      </div>
    </div>
  );
}

export default SavedNotifications;
