import React from "react";
import { useNotification, NotificationItem } from "./notification-context";

const h = React.createElement;

interface NotificationPopupProps {
  onClose: () => void;
}

export function NotificationPopup({ onClose }: NotificationPopupProps) {
  const { notifications, removeNotification, clearNotifications } = useNotification();
  const listRef = React.useRef<HTMLDivElement>(null);

  React.useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (listRef.current && !listRef.current.contains(event.target as Node)) {
        onClose();
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [onClose]);

  if (notifications.length === 0) {
    return h("div", { className: "notification-popup", ref: listRef },
      h("div", { className: "notification-popup-header" },
        h("span", null, "通知"),
        h("button", { className: "notification-popup-close", onClick: onClose }, "×"),
      ),
      h("div", { className: "notification-popup-empty" }, "暂无通知"),
    );
  }

  return h("div", { className: "notification-popup", ref: listRef },
    h("div", { className: "notification-popup-header" },
      h("span", null, `通知 (${notifications.length})`),
      h("div", { className: "notification-popup-actions" },
        h("button", { className: "notification-popup-clear", onClick: clearNotifications }, "清空"),
        h("button", { className: "notification-popup-close", onClick: onClose }, "×"),
      ),
    ),
    h("div", { className: "notification-popup-list" },
      notifications.slice().reverse().map((item: NotificationItem) =>
        h("div", {
          key: item.id,
          className: `notification-item ${item.type}`,
        },
          h("span", { className: "notification-item-icon" }, item.type === "success" ? "✓" : "×"),
          h("span", { className: "notification-item-message" }, item.message),
          h("button", {
            className: "notification-item-dismiss",
            onClick: () => removeNotification(item.id),
          }, "×"),
        )
      ),
    ),
  );
}

export function NotificationBanner({ notification }: { notification: NotificationItem }) {
  const { removeNotification } = useNotification();

  React.useEffect(() => {
    const timer = setTimeout(() => {
      removeNotification(notification.id);
    }, 3000);
    return () => clearTimeout(timer);
  }, [notification.id, removeNotification]);

  return h("div", {
    className: `notification-banner ${notification.type}`,
    role: "alert",
  },
    h("span", { className: "notification-banner-icon" }, notification.type === "success" ? "✓" : "×"),
    h("span", { className: "notification-banner-message" }, notification.message),
    h("button", {
      className: "notification-banner-dismiss",
      onClick: () => removeNotification(notification.id),
    }, "×"),
  );
}