import { useEffect, useRef, useState } from 'react';
import { router } from '@inertiajs/react';

type Notification = {
  id: number;
  type: string;
  title: string;
  body: string;
  link: string | null;
  read: boolean;
  time: string;
};

export function NotificationBell() {
  const [count, setCount] = useState(0);
  const [open, setOpen] = useState(false);
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [loading, setLoading] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

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

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

  function fetchCount() {
    fetch('/api/notifications/unread-count', {
      headers: { Accept: 'application/json' },
      credentials: 'same-origin',
    })
      .then((r) => r.json())
      .then((d) => setCount(d.count ?? 0))
      .catch(() => {});
  }

  function openPanel() {
    setOpen((v) => !v);
    if (!open) {
      setLoading(true);
      fetch('/api/notifications', {
        headers: { Accept: 'application/json' },
        credentials: 'same-origin',
      })
        .then((r) => r.json())
        .then((d) => { setNotifications(d.notifications ?? []); setLoading(false); })
        .catch(() => setLoading(false));
    }
  }

  function markAllRead() {
    const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '';
    fetch('/api/notifications/mark-read', {
      method: 'POST',
      headers: { 'X-CSRF-TOKEN': token, 'Content-Type': 'application/json', Accept: 'application/json' },
      credentials: 'same-origin',
    }).then(() => {
      setCount(0);
      setNotifications((ns) => ns.map((n) => ({ ...n, read: true })));
    }).catch(() => {});
  }

  function handleNotifClick(n: Notification) {
    const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '';
    if (!n.read) {
      fetch('/api/notifications/mark-read', {
        method: 'POST',
        headers: { 'X-CSRF-TOKEN': token, 'Content-Type': 'application/json', Accept: 'application/json' },
        credentials: 'same-origin',
        body: JSON.stringify({ id: n.id }),
      }).then(() => {
        setNotifications((ns) => ns.map((x) => x.id === n.id ? { ...x, read: true } : x));
        setCount((c) => Math.max(0, c - 1));
      }).catch(() => {});
    }
    if (n.link) {
      setOpen(false);
      router.visit(n.link);
    }
  }

  return (
    <div className="notif-bell" ref={ref}>
      <button type="button" className={`topbar-icon-btn${count > 0 ? ' topbar-icon-btn--ringing' : ''}`} onClick={openPanel} aria-label="اعلان‌ها">
        <i className="bi bi-bell" />
        {count > 0 && <span className="notif-badge">{count > 99 ? '۹۹+' : count}</span>}
      </button>

      {open && (
        <div className="notif-panel">
          <div className="notif-panel-head">
            <span>اعلان‌ها</span>
            {count > 0 && (
              <button type="button" className="notif-markall" onClick={markAllRead}>
                همه خوانده شد
              </button>
            )}
          </div>
          <div className="notif-list">
            {loading && <div className="notif-empty">در حال بارگذاری...</div>}
            {!loading && notifications.length === 0 && (
              <div className="notif-empty">اعلانی وجود ندارد</div>
            )}
            {!loading && notifications.map((n) => (
              <button
                key={n.id}
                type="button"
                className={`notif-item${n.read ? '' : ' notif-item--unread'}${n.link ? ' notif-item--link' : ''}`}
                onClick={() => handleNotifClick(n)}
              >
                <span className="notif-dot" />
                <span className="notif-content">
                  <span className="notif-title">{n.title}</span>
                  {n.body && <span className="notif-body">{n.body}</span>}
                  <span className="notif-time">{n.time}</span>
                </span>
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
