'use client';

import { useState, useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation';
import {
  getNotifications, markAllRead, clearNotifications, formatRelative,
  type Notification
} from '@/lib/notifications';

const MODULE_ICONS: Record<string, React.ReactNode> = {
  orders:    <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" /></svg>,
  products:  <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" /></svg>,
  customers: <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" /></svg>,
  farms:     <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3.055 11H5a2 2 0 012 2v1a2 2 0 002 2 2 2 0 012 2v2.945M8 3.935V5.5A2.5 2.5 0 0010.5 8h.5a2 2 0 012 2 2 2 0 104 0 2 2 0 012-2h1.064" /></svg>,
};

export default function NotificationBell({ onRefresh }: { onRefresh?: (module: string) => void }) {
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [open, setOpen] = useState(false);
  const panelRef = useRef<HTMLDivElement>(null);
  const router = useRouter();

  const load = () => setNotifications(getNotifications());

  useEffect(() => {
    load();
    const handler = () => load();
    window.addEventListener('usfloral-notification', handler);
    return () => window.removeEventListener('usfloral-notification', handler);
  }, []);

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

  const unread = notifications.filter(n => !n.read).length;

  const handleOpen = () => {
    setOpen(v => !v);
    if (!open) { markAllRead(); load(); }
  };

  const handleGoTo = (notif: Notification) => {
    setOpen(false);
    router.push(notif.link);
  };

  return (
    <div style={{ position: 'relative' }} ref={panelRef}>
      {/* Bell button */}
      <button
        onClick={handleOpen}
        title="Notificaciones"
        style={{
          position: 'relative', background: open ? 'rgba(28,82,54,0.12)' : 'transparent',
          border: '1px solid var(--border-color)', borderRadius: '10px',
          padding: '0.5rem', cursor: 'pointer', color: 'var(--primary-color)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          transition: 'all 0.2s',
        }}
      >
        <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
        </svg>
        {unread > 0 && (
          <span style={{
            position: 'absolute', top: '-4px', right: '-4px',
            background: 'var(--secondary-color)', color: 'white',
            borderRadius: '999px', fontSize: '0.6rem', fontWeight: 800,
            width: '16px', height: '16px', display: 'flex', alignItems: 'center', justifyContent: 'center',
            animation: 'pulse-badge 2s ease infinite',
          }}>
            {unread > 9 ? '9+' : unread}
          </span>
        )}
      </button>

      {/* Dropdown panel */}
      {open && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 10px)', right: 0,
          width: '340px', background: 'white',
          borderRadius: 'var(--radius-lg)', border: '1px solid var(--border-color)',
          boxShadow: '0 20px 50px rgba(0,0,0,0.12)', zIndex: 200,
          animation: 'dropdownIn 0.2s ease',
          overflow: 'hidden',
        }}>
          {/* Header */}
          <div style={{
            padding: '1rem 1.25rem', borderBottom: '1px solid var(--border-color)',
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            background: 'linear-gradient(135deg, var(--primary-color), #297750)',
          }}>
            <div>
              <p style={{ color: 'white', fontWeight: 700, fontSize: '0.9rem' }}>Notificaciones</p>
              <p style={{ color: 'rgba(255,255,255,0.7)', fontSize: '0.72rem' }}>
                {notifications.length === 0 ? 'Sin actividad reciente' : `${notifications.length} eventos registrados`}
              </p>
            </div>
            {notifications.length > 0 && (
              <button onClick={clearNotifications} style={{
                color: 'rgba(255,255,255,0.7)', fontSize: '0.7rem', cursor: 'pointer',
                border: '1px solid rgba(255,255,255,0.3)', borderRadius: '6px', padding: '0.25rem 0.5rem',
                fontWeight: 600, transition: 'all 0.2s', background: 'transparent',
              }}
                onMouseEnter={e => (e.currentTarget.style.background = 'rgba(255,255,255,0.15)')}
                onMouseLeave={e => (e.currentTarget.style.background = 'transparent')}
              >
                Limpiar
              </button>
            )}
          </div>

          {/* List */}
          <div style={{ maxHeight: '320px', overflowY: 'auto' }}>
            {notifications.length === 0 ? (
              <div style={{ padding: '2.5rem 1.5rem', textAlign: 'center', color: 'var(--text-secondary)' }}>
                <svg width="32" height="32" fill="none" stroke="currentColor" viewBox="0 0 24 24" style={{ margin: '0 auto 0.75rem', opacity: 0.3 }}>
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
                </svg>
                <p style={{ fontSize: '0.8rem', fontWeight: 500 }}>Sin notificaciones</p>
              </div>
            ) : notifications.map((notif) => (
              <div key={notif.id} style={{
                padding: '0.875rem 1.25rem',
                borderBottom: '1px solid rgba(0,0,0,0.04)',
                background: notif.read ? 'white' : 'rgba(28,82,54,0.04)',
                display: 'flex', gap: '0.75rem', alignItems: 'flex-start',
              }}>
                <div style={{
                  width: '28px', height: '28px', borderRadius: '8px', flexShrink: 0, marginTop: '2px',
                  background: 'rgba(28,82,54,0.08)', color: 'var(--primary-color)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  {MODULE_ICONS[notif.module] || MODULE_ICONS['orders']}
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <p style={{ fontSize: '0.8rem', fontWeight: notif.read ? 400 : 600, color: 'var(--text-primary)', marginBottom: '0.15rem', lineHeight: 1.4 }}>{notif.message}</p>
                  <p style={{ fontSize: '0.7rem', color: 'var(--text-secondary)' }}>{formatRelative(notif.timestamp)}</p>
                </div>
                <button
                  onClick={() => handleGoTo(notif)}
                  title="Ir al módulo"
                  style={{
                    flexShrink: 0, padding: '0.3rem 0.6rem', borderRadius: '6px',
                    background: 'rgba(28,82,54,0.08)', color: 'var(--primary-color)',
                    border: 'none', cursor: 'pointer', fontSize: '0.7rem', fontWeight: 600,
                    transition: 'background 0.2s', whiteSpace: 'nowrap',
                  }}
                  onMouseEnter={e => (e.currentTarget.style.background = 'rgba(28,82,54,0.16)')}
                  onMouseLeave={e => (e.currentTarget.style.background = 'rgba(28,82,54,0.08)')}
                >
                  Ver →
                </button>
              </div>
            ))}
          </div>
        </div>
      )}

      <style>{`
        @keyframes pulse-badge { 0%,100%{transform:scale(1)} 50%{transform:scale(1.2)} }
        @keyframes dropdownIn { from{opacity:0;transform:translateY(-8px)} to{opacity:1;transform:translateY(0)} }
      `}</style>
    </div>
  );
}
