import type { FC } from 'react';
import { useEffect, useRef, useState, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { Bell, Boxes, CalendarX, Clock, Target, MessageSquare } from 'lucide-react';
import { odooApi, type AppNotification } from '../services/odoo';

const TIPO_ICON: Record<string, typeof Boxes> = {
  stock_bajo: Boxes,
  caducidades: CalendarX,
  citas_pendientes_hoy: Clock,
  leads_sin_asignar: Target,
  conversaciones_sin_leer: MessageSquare,
};

const SEVERITY_CLASS: Record<string, string> = {
  info: 'bg-theme-accent-bg text-theme-heading',
  warning: 'bg-theme-warning text-theme-warning-text',
  danger: 'bg-rose-100 text-rose-700',
};

interface NotificationBellProps {
  buttonClassName?: string;
}

export const NotificationBell: FC<NotificationBellProps> = ({ buttonClassName }) => {
  const navigate = useNavigate();
  const [notifications, setNotifications] = useState<AppNotification[]>([]);
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(true);
  const ref = useRef<HTMLDivElement>(null);

  const load = useCallback(async () => {
    try {
      const res = await odooApi.getNotifications();
      if (res.status === 'success') setNotifications(res.notifications);
    } catch {
      // silencioso: la campanita no debe molestar si falla
    } finally {
      setLoading(false);
    }
  }, []);

  // Polling 60s + al enfocar la ventana
  useEffect(() => {
    load();
    const interval = setInterval(load, 60000);
    const onFocus = () => load();
    window.addEventListener('focus', onFocus);
    return () => {
      clearInterval(interval);
      window.removeEventListener('focus', onFocus);
    };
  }, [load]);

  useEffect(() => {
    if (!open) return;
    const close = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener('mousedown', close);
    return () => document.removeEventListener('mousedown', close);
  }, [open]);

  const total = notifications.length;

  return (
    <div ref={ref} className="relative">
      <button
        type="button"
        onClick={() => setOpen((v) => !v)}
        title="Notificaciones"
        aria-label="Notificaciones"
        className={buttonClassName || 'p-2 rounded-full relative transition text-theme-muted hover:bg-theme-accent-bg hover:text-theme-heading'}
      >
        <Bell size={18} />
        {total > 0 && (
          <span className="absolute -top-0.5 -right-0.5 min-w-[16px] h-4 px-1 rounded-full bg-rose-500 text-white text-[10px] font-bold flex items-center justify-center">
            {total}
          </span>
        )}
      </button>

      {open && (
        <div className="absolute right-0 top-full mt-2 z-50 w-80 rounded-2xl border border-theme-border bg-theme-surface shadow-card overflow-hidden">
          <p className="px-4 py-2.5 text-xs font-medium text-theme-muted uppercase border-b border-theme-border">
            Notificaciones
          </p>
          {loading && notifications.length === 0 ? (
            <p className="text-sm text-theme-muted text-center py-6">Cargando...</p>
          ) : notifications.length === 0 ? (
            <p className="text-sm text-theme-muted text-center py-6">Sin notificaciones</p>
          ) : (
            <ul className="max-h-80 overflow-y-auto">
              {notifications.map((n) => {
                const Icon = TIPO_ICON[n.tipo] || Bell;
                return (
                  <li key={n.tipo}>
                    <button
                      type="button"
                      onClick={() => { setOpen(false); navigate(n.link); }}
                      className="w-full flex items-start gap-3 px-4 py-3 text-left hover:bg-theme-bg transition border-b border-theme-border last:border-0"
                    >
                      <span className={`mt-0.5 w-7 h-7 rounded-full flex items-center justify-center shrink-0 ${SEVERITY_CLASS[n.severity] || SEVERITY_CLASS.info}`}>
                        <Icon size={14} />
                      </span>
                      <span className="min-w-0">
                        <span className="block text-sm font-medium text-theme-heading truncate">{n.titulo}</span>
                        <span className="block text-xs text-theme-muted truncate">{n.detalle}</span>
                      </span>
                    </button>
                  </li>
                );
              })}
            </ul>
          )}
        </div>
      )}
    </div>
  );
};

export default NotificationBell;
