import React, { useEffect, useId, useRef, useState } from "react";
import { assignmentNotificationMessage } from "../../utils/assignmentNotifications.js";
import { formatRelativeTime } from "../../utils/recentActivity.js";

/**
 * @param {{
 *   unread?: object[],
 *   onMarkRead?: (row: object) => void,
 *   onMarkAllRead?: () => void,
 *   onOpenAssignment?: (documentId: number, documentNumber: number, row: object) => void,
 *   onViewAll?: () => void,
 * }} props
 */
export default function AssignmentNotificationBell({
  unread = [],
  onMarkRead,
  onMarkAllRead,
  onOpenAssignment,
  onViewAll,
}) {
  const [open, setOpen] = useState(false);
  const rootRef = useRef(null);
  const panelId = useId();
  const count = unread.length;

  useEffect(() => {
    if (!open) return undefined;

    const onPointerDown = (event) => {
      if (rootRef.current && !rootRef.current.contains(event.target)) {
        setOpen(false);
      }
    };

    const onKeyDown = (event) => {
      if (event.key === "Escape") setOpen(false);
    };

    document.addEventListener("mousedown", onPointerDown);
    document.addEventListener("keydown", onKeyDown);
    return () => {
      document.removeEventListener("mousedown", onPointerDown);
      document.removeEventListener("keydown", onKeyDown);
    };
  }, [open]);

  const handleOpenItem = (row) => {
    onMarkRead?.(row);
    setOpen(false);
    onOpenAssignment?.(row.document_id, row.document_number, row);
  };

  const handleViewAll = () => {
    setOpen(false);
    onMarkAllRead?.();
    onViewAll?.();
  };

  return (
    <div className="portal-notify" ref={rootRef}>
      <button
        type="button"
        className="portal-icon-btn portal-notify__bell"
        aria-label={
          count
            ? `${count} new SWI assignment${count === 1 ? "" : "s"}`
            : "Assignment notifications"
        }
        aria-expanded={open}
        aria-controls={panelId}
        onClick={() => setOpen((value) => !value)}
      >
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden>
          <path d="M18 8a6 6 0 1 0-12 0c0 7-3 9-3 9h18s-3-2-3-9" />
          <path d="M13.73 21a2 2 0 0 1-3.46 0" />
        </svg>
        {count > 0 ? (
          <span className="portal-notify__badge" aria-hidden>
            {count > 99 ? "99+" : count}
          </span>
        ) : null}
      </button>

      {open ? (
        <div id={panelId} className="portal-notify__panel" role="dialog" aria-label="Assignment notifications">
          <header className="portal-notify__head">
            <h2 className="portal-notify__title">Assignments</h2>
            {count > 0 ? (
              <button
                type="button"
                className="portal-notify__mark-all"
                onClick={() => onMarkAllRead?.()}
              >
                Mark all read
              </button>
            ) : null}
          </header>

          {!count ? (
            <p className="portal-notify__empty">No new assignments.</p>
          ) : (
            <ul className="portal-notify__list">
              {unread.map((row) => {
                const key = `${row.document_id}-${row.document_number}-${row.assigned_at}`;
                const message = assignmentNotificationMessage(row);
                return (
                  <li key={key}>
                    <button
                      type="button"
                      className="portal-notify__item"
                      onClick={() => handleOpenItem(row)}
                    >
                      <span className="portal-notify__item-title">{message.title}</span>
                      <span className="portal-notify__item-body">{message.body}</span>
                      <span className="portal-notify__item-time">
                        {formatRelativeTime(row.assigned_at)}
                      </span>
                    </button>
                  </li>
                );
              })}
            </ul>
          )}

          <footer className="portal-notify__foot">
            <button type="button" className="portal-notify__view-all" onClick={handleViewAll}>
              View assigned SWIs
            </button>
          </footer>
        </div>
      ) : null}
    </div>
  );
}
