import React, { useEffect, useId, useRef, useState } from "react";

function formatWhen(value) {
  if (!value) return "";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "";
  return date.toLocaleString(undefined, {
    month: "short",
    day: "numeric",
    hour: "numeric",
    minute: "2-digit"
  });
}

export default function HandoverNotificationBell({
  unread = [],
  loading = false,
  onMarkRead,
  onMarkAllRead,
  onOpenPermit
}) {
  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 = async (row) => {
    await onMarkRead?.(row);
    setOpen(false);
    onOpenPermit?.(row);
  };

  return (
    <div className="portal-notify" ref={rootRef}>
      <button
        type="button"
        className="portal-icon-btn portal-notify__bell"
        aria-label={
          count
            ? `${count} new PTW handover notification${count === 1 ? "" : "s"}`
            : "PTW handover 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="PTW handover notifications">
          <header className="portal-notify__head">
            <h2 className="portal-notify__title">Handovers</h2>
            {count > 0 ? (
              <button
                type="button"
                className="portal-notify__mark-all"
                onClick={() => onMarkAllRead?.()}
              >
                Mark all read
              </button>
            ) : null}
          </header>

          {loading ? (
            <p className="portal-notify__empty">Loading…</p>
          ) : !count ? (
            <p className="portal-notify__empty">No new handover notifications.</p>
          ) : (
            <ul className="portal-notify__list">
              {unread.map((row) => (
                <li key={row.notification_id}>
                  <button
                    type="button"
                    className="portal-notify__item"
                    onClick={() => handleOpenItem(row)}
                  >
                    <span className="portal-notify__item-title">
                      {row.permit_number || `Permit #${row.permit_id}`}
                    </span>
                    <span className="portal-notify__item-body">{row.message}</span>
                    {row.handed_by_name ? (
                      <span className="portal-notify__item-body">
                        From {row.handed_by_name}
                      </span>
                    ) : null}
                    <span className="portal-notify__item-time">{formatWhen(row.created_at)}</span>
                  </button>
                </li>
              ))}
            </ul>
          )}
        </div>
      ) : null}
    </div>
  );
}
