import { useState, useEffect, useRef } from 'react';
import { Bell, X, ShoppingBag, Clock } from 'lucide-react';
import { CotacaoService, InboxInternoService } from '../services/api';

function fmtHora(d: string) {
  const dt = new Date(d);
  const diff = Date.now() - dt.getTime();
  if (diff < 60_000) return 'agora';
  if (diff < 3_600_000) return `${Math.floor(diff / 60_000)}min atrás`;
  if (diff < 86_400_000) return `${Math.floor(diff / 3_600_000)}h atrás`;
  return dt.toLocaleDateString('pt-BR');
}

const STATUS_COLOR: Record<string, string> = {
  aguardando: 'bg-slate-600',
  separacao:  'bg-blue-500',
  embalagem:  'bg-violet-500',
  auditoria:  'bg-amber-500',
  fiscal:     'bg-cyan-500',
  expedicao:  'bg-orange-500',
  entregue:   'bg-emerald-500',
  cancelado:  'bg-rose-500',
};

export default function NotificacoesBell() {
  const [open, setOpen] = useState(false);
  const [pedidos, setPedidos] = useState<any[]>([]);
  const [inboxTotal, setInboxTotal] = useState(0);
  const [total, setTotal] = useState(0);
  const panelRef = useRef<HTMLDivElement>(null);

  async function carregar() {
    try {
      const [p, inbox] = await Promise.all([
        CotacaoService.notificacoes(1440),
        InboxInternoService.contadores(),
      ]);
      // Pedidos criados hoje
      const hoje = new Date();
      hoje.setHours(0, 0, 0, 0);
      const novosHoje = (p as any[]).filter(x => new Date(x.created_at) >= hoje);
      setPedidos(novosHoje.slice(0, 10));
      setInboxTotal(inbox.total);
      setTotal(novosHoje.length + inbox.total);
    } catch { /* silent */ }
  }

  useEffect(() => {
    carregar();
    const iv = setInterval(carregar, 30_000);
    return () => clearInterval(iv);
  }, []);

  // Fecha ao clicar fora
  useEffect(() => {
    function handler(e: MouseEvent) {
      if (panelRef.current && !panelRef.current.contains(e.target as Node)) {
        setOpen(false);
      }
    }
    if (open) document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [open]);

  return (
    <div className="relative" ref={panelRef}>
      <button
        onClick={() => setOpen(o => !o)}
        className="relative p-2 rounded-lg text-slate-400 hover:text-white hover:bg-white/5 transition-colors"
        title="Notificações"
      >
        <Bell size={18} />
        {total > 0 && (
          <span className="absolute -top-0.5 -right-0.5 bg-rose-500 text-white text-[10px] font-black w-4 h-4 rounded-full flex items-center justify-center leading-none">
            {total > 9 ? '9+' : total}
          </span>
        )}
      </button>

      {open && (
        <div className="absolute right-0 top-full mt-2 w-80 bg-slate-900 border border-white/10 rounded-xl shadow-2xl z-50 overflow-hidden">
          {/* Header */}
          <div className="flex items-center justify-between px-4 py-3 border-b border-white/10">
            <span className="text-sm font-bold text-white flex items-center gap-2">
              <Bell size={14} className="text-amber-400" /> Notificações
            </span>
            <button onClick={() => setOpen(false)} className="text-slate-500 hover:text-white">
              <X size={14} />
            </button>
          </div>

          <div className="max-h-96 overflow-y-auto">
            {/* Inbox badge */}
            {inboxTotal > 0 && (
              <div className="px-4 py-2.5 border-b border-white/5 flex items-center gap-3 bg-amber-500/5">
                <div className="w-7 h-7 rounded-full bg-amber-500/20 flex items-center justify-center shrink-0">
                  <Bell size={13} className="text-amber-400" />
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-xs font-semibold text-white">Inbox interno</p>
                  <p className="text-[11px] text-amber-400">{inboxTotal} mensagen{inboxTotal !== 1 ? 's' : ''} não lida{inboxTotal !== 1 ? 's' : ''}</p>
                </div>
              </div>
            )}

            {/* Pedidos de hoje */}
            {pedidos.length === 0 && inboxTotal === 0 ? (
              <div className="px-4 py-8 text-center text-slate-500 text-sm">
                Nenhuma notificação nova
              </div>
            ) : (
              pedidos.map(p => (
                <div key={p.id} className="px-4 py-2.5 border-b border-white/5 flex items-center gap-3 hover:bg-white/3 transition-colors">
                  <div className={`w-2 h-2 rounded-full shrink-0 ${STATUS_COLOR[p.status] ?? 'bg-slate-600'}`} />
                  <div className="flex-1 min-w-0">
                    <p className="text-xs font-semibold text-white truncate">
                      Pedido #{p.id}
                      {p.total ? ` — R$ ${Number(p.total).toFixed(2).replace('.', ',')}` : ''}
                    </p>
                    <p className="text-[11px] text-slate-500 flex items-center gap-1">
                      <Clock size={10} /> {fmtHora(p.created_at)}
                      <span className="ml-1 capitalize">{p.status}</span>
                    </p>
                  </div>
                  <ShoppingBag size={13} className="text-slate-600 shrink-0" />
                </div>
              ))
            )}
          </div>

          {/* Footer */}
          {(pedidos.length > 0 || inboxTotal > 0) && (
            <div className="px-4 py-2 border-t border-white/10">
              <button
                onClick={() => { setOpen(false); carregar(); }}
                className="text-xs text-amber-400 hover:text-amber-300 transition-colors"
              >
                Atualizar
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
