'use client';
import { useState, useEffect, useRef } from 'react';

interface Notification {
  id: string;
  type: 'pending_orders' | 'stale_shipped' | 'awaiting_payment';
  count: number;
  message: string;
  href: string;
}

const ICONS: Record<string, string> = {
  pending_orders: '📦',
  stale_shipped: '🚚',
  awaiting_payment: '💳',
};

export function BellNotifications() {
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  const load = async () => {
    try {
      const res = await fetch('/api/backoffice/notifications', { credentials: 'include' });
      if (!res.ok) return;
      const data = await res.json() as { items?: Notification[] };
      setNotifications(data.items ?? []);
    } catch { /* silent */ }
  };

  useEffect(() => { void load(); void setInterval(load, 60_000); }, []);

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

  const total = notifications.reduce((s, n) => s + n.count, 0);

  return (
    <div ref={ref} className="relative">
      <button type="button" onClick={() => setOpen((v) => !v)}
        className="relative p-2 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-xl transition-colors"
        title="Notificaciones">
        <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
          <path strokeLinecap="round" strokeLinejoin="round"
            d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 15.638V17m0 0V21m0-4H9.5a3.5 3.5 0 100-7 3.5 3.5 0 000 7zm0 0H6m6 0a3 3 0 11-6 0 3 3 0 016 0z" />
        </svg>
        {total > 0 && (
          <span className="absolute -top-1 -right-1 flex h-5 w-5 items-center justify-center rounded-full bg-red-500 text-[10px] font-bold text-white">
            {total > 99 ? '99+' : total}
          </span>
        )}
      </button>

      {open && (
        <div className="absolute right-0 top-full mt-2 w-80 bg-white border border-gray-200 rounded-2xl shadow-xl z-50 overflow-hidden">
          <div className="px-4 py-3 border-b border-gray-100 flex items-center justify-between">
            <h3 className="font-semibold text-gray-900 text-sm">Notificaciones</h3>
            <button onClick={() => void load()} className="text-xs text-gray-400 hover:text-gray-600">
              🔄 Actualizar
            </button>
          </div>
          <div className="max-h-72 overflow-y-auto">
            {notifications.length === 0 ? (
              <div className="px-4 py-8 text-center text-gray-400 text-sm">
                ✨ Todo en orden
              </div>
            ) : (
              notifications.map((n) => (
                <a key={n.id} href={n.href}
                  className="flex items-start gap-3 px-4 py-3 hover:bg-gray-50 border-b border-gray-50 last:border-0 transition-colors"
                  onClick={() => setOpen(false)}>
                  <span className="text-xl shrink-0">{ICONS[n.type]}</span>
                  <div className="min-w-0">
                    <p className="text-sm text-gray-900 font-medium">{n.message}</p>
                    <p className="text-xs text-gray-400 mt-0.5">{n.count} pedido{n.count !== 1 ? 's' : ''}</p>
                  </div>
                </a>
              ))
            )}
          </div>
          {total > 0 && (
            <div className="px-4 py-2 bg-gray-50 border-t border-gray-100">
              <a href="/orders" onClick={() => setOpen(false)}
                className="text-xs text-[#2D6A4F] font-medium hover:underline">
                Ver todos los pedidos →
              </a>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
