'use client';
import { useEffect, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import { Bell, CheckCheck, Rss, BellRing, Megaphone } from 'lucide-react';
import { api } from '@/lib/api';
import { getSocket } from '@/lib/socket';
import { useAuth } from '@/context/AuthContext';
import { useToast } from '@/context/ToastContext';
import { useAlerts } from '@/context/AlertContext';
import { timeAgo } from '@/lib/time';

const ICONS = {
  feed_post: Rss,
  admin_announcement: Megaphone,
  reminder: BellRing,
};

// Map notification type -> alert modal style
const ALERT_TYPE = {
  feed_post: 'info',
  admin_announcement: 'success',
  reminder: 'warning',
};

export default function NotificationBell() {
  const { token } = useAuth();
  const { push } = useToast();
  const { alert } = useAlerts();
  const router = useRouter();

  const [open, setOpen] = useState(false);
  const [items, setItems] = useState([]);
  const [unread, setUnread] = useState(0);
  const [loading, setLoading] = useState(true);
  const wrapRef = useRef(null);

  // ── Initial load ──
  useEffect(() => {
    if (!token) return;
    (async () => {
      try {
        const { notifications, unreadCount } = await api('/notifications', { token });
        setItems(notifications);
        setUnread(unreadCount);
      } catch {}
      setLoading(false);
    })();
  }, [token]);

  // ── Live notifications ──
  useEffect(() => {
    const socket = getSocket();
    if (!socket) return;

    const onNew = (n) => {
      setItems((prev) => (prev.some((p) => p.id === n.id) ? prev : [n, ...prev]));
      setUnread((u) => u + 1);

      // Small toast in the corner
      push(n.title, 'info');

      // 🔊 + 🎯 Big center alert with sound
      alert({
        type: ALERT_TYPE[n.type] || 'info',
        title: n.title,
        message: n.body,
        link: n.link,
        actionLabel: 'Open',
      });
    };

    socket.on('notification:new', onNew);
    return () => socket.off('notification:new', onNew);
  }, [push, alert]);

  // ── Click outside → close dropdown ──
  useEffect(() => {
    function handle(e) {
      if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);
    }
    if (open) document.addEventListener('mousedown', handle);
    return () => document.removeEventListener('mousedown', handle);
  }, [open]);

  async function markOneRead(id) {
    const n = items.find((x) => x.id === id);
    if (!n || n.isRead) return;
    setItems((prev) => prev.map((x) => (x.id === id ? { ...x, isRead: 1 } : x)));
    setUnread((u) => Math.max(0, u - 1));
    try {
      await api('/notifications/read', { method: 'POST', body: { ids: [id] }, token });
    } catch {}
  }

  async function markAllRead() {
    setItems((prev) => prev.map((x) => ({ ...x, isRead: 1 })));
    setUnread(0);
    try {
      await api('/notifications/read-all', { method: 'POST', token });
    } catch {}
  }

  function handleClick(n) {
    markOneRead(n.id);
    if (n.link) {
      setOpen(false);
      router.push(n.link);
    }
  }

  return (
    <div className="relative" ref={wrapRef}>
      <button
        onClick={() => setOpen((v) => !v)}
        className="relative h-9 w-9 grid place-items-center rounded-lg
                   border border-ink-200 bg-white hover:bg-ink-50 transition
                   text-ink-600 hover:text-ink-900"
        title="Notifications"
      >
        <Bell size={16} />
        {unread > 0 && (
          <span className="absolute -top-1 -right-1 min-w-[18px] h-[18px] px-1
                           grid place-items-center rounded-full
                           bg-brand-600 text-white text-[10px] font-bold
                           ring-2 ring-white">
            {unread > 99 ? '99+' : unread}
          </span>
        )}
      </button>

      {open && (
        <div className="absolute right-0 top-[calc(100%+8px)] w-[380px] z-50
                        bg-white rounded-xl border border-ink-200 shadow-pop
                        animate-pop-in origin-top-right overflow-hidden">
          <div className="flex items-center justify-between px-4 py-3
                          border-b border-ink-200">
            <p className="text-[13px] font-bold text-ink-900">
              Notifications
              {unread > 0 && (
                <span className="ml-2 text-[11px] font-semibold text-brand-600">
                  {unread} new
                </span>
              )}
            </p>
            {unread > 0 && (
              <button onClick={markAllRead}
                className="flex items-center gap-1 text-[11px] font-semibold
                           text-brand-600 hover:text-brand-700 transition">
                <CheckCheck size={12} />
                Mark all read
              </button>
            )}
          </div>

          <div className="max-h-[400px] overflow-y-auto">
            {loading ? (
              <div className="p-6 text-center text-xs text-ink-500">Loading...</div>
            ) : items.length === 0 ? (
              <div className="p-8 text-center">
                <Bell size={28} className="mx-auto text-ink-300 mb-2" />
                <p className="text-[13px] font-medium text-ink-700">You&apos;re all caught up</p>
                <p className="text-[11px] text-ink-500 mt-1">
                  New notifications will appear here.
                </p>
              </div>
            ) : (
              items.map((n) => {
                const Icon = ICONS[n.type] || Bell;
                return (
                  <button
                    key={n.id}
                    onClick={() => handleClick(n)}
                    className={`w-full text-left flex items-start gap-3 px-4 py-3
                                border-b border-ink-100 last:border-0
                                hover:bg-ink-50 transition
                                ${!n.isRead ? 'bg-brand-50/50' : ''}`}
                  >
                    <div className={`shrink-0 h-8 w-8 rounded-lg grid place-items-center
                      ${!n.isRead
                        ? 'bg-brand-100 text-brand-600'
                        : 'bg-ink-100 text-ink-500'}`}>
                      <Icon size={14} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className={`text-[13px] leading-snug
                        ${!n.isRead ? 'font-semibold text-ink-900' : 'font-medium text-ink-700'}`}>
                        {n.title}
                      </p>
                      {n.body && (
                        <p className="text-[12px] text-ink-500 mt-0.5 line-clamp-2">
                          {n.body}
                        </p>
                      )}
                      <p className="text-[10px] text-ink-400 mt-1 font-medium">
                        {timeAgo(n.createdAt)}
                      </p>
                    </div>
                    {!n.isRead && (
                      <span className="shrink-0 mt-2 h-2 w-2 rounded-full bg-brand-500" />
                    )}
                  </button>
                );
              })
            )}
          </div>
        </div>
      )}
    </div>
  );
}