"use client";
import {
  createContext,
  useCallback,
  useContext,
  useEffect,
  useRef,
  useState,
  type ReactNode,
} from "react";
import { createPortal } from "react-dom";
import SystemAlert, { type SystemAlertProps } from "./SystemAlert";
type Notice = Omit<SystemAlertProps, "onClose" | "className"> & { id?: string };
export type SessionNotice = Notice & { id: string; unread: boolean };
type NotificationContext = {
  notify: (notice: Notice) => void;
  notifications: SessionNotice[];
  markRead: () => void;
  clearNotifications: () => void;
};
const Context = createContext<NotificationContext | null>(null);
export default function SystemNotifications({ children }: { children: ReactNode }) {
  const [notices, setNotices] = useState<(Notice & { id: string })[]>([]);
  const [notifications, setNotifications] = useState<SessionNotice[]>([]);
  const sequence = useRef(0);
  useEffect(() => {
    if (!notices.length) return;
    const timer = window.setTimeout(() => setNotices((current) => current.slice(1)), 8000);
    return () => window.clearTimeout(timer);
  }, [notices]);
  const notify = useCallback((notice: Notice) => {
    const id = notice.id ?? `notice-${++sequence.current}`;
    setNotices((current) =>
      [...current.filter((item) => item.id !== id), { ...notice, id }].slice(-3),
    );
    setNotifications((current) =>
      [{ ...notice, id, unread: true }, ...current.filter((item) => item.id !== id)].slice(0, 20),
    );
  }, []);
  const markRead = useCallback(
    () => setNotifications((current) => current.map((item) => ({ ...item, unread: false }))),
    [],
  );
  const clearNotifications = useCallback(() => {
    setNotifications([]);
    setNotices([]);
  }, []);
  return (
    <Context.Provider value={{ notify, notifications, markRead, clearNotifications }}>
      {children}
      {notices.length > 0 &&
        createPortal(
          <div
            aria-label="Avisos del sistema"
            style={{ top: "calc(var(--system-header-height, 0px) + 1rem)" }}
            className="pointer-events-none fixed right-4 left-4 z-[10000] flex flex-col gap-3 sm:left-auto sm:w-[min(28rem,calc(100vw-2rem))]"
          >
            {notices.map((notice) => (
              <SystemAlert
                key={notice.id}
                {...notice}
                className="pointer-events-auto shadow-lg"
                onClose={() =>
                  setNotices((current) => current.filter((item) => item.id !== notice.id))
                }
              />
            ))}
          </div>,
          document.body,
        )}
    </Context.Provider>
  );
}
export function useSystemNotifications() {
  const context = useContext(Context);
  if (!context) throw new Error("SystemNotifications debe estar instalado en el layout principal.");
  return context;
}
