import React from "react";

export type NotificationType = "success" | "error";

export interface NotificationItem {
  id: string;
  type: NotificationType;
  message: string;
  timestamp: number;
}

export interface NotificationContextValue {
  notifications: NotificationItem[];
  addNotification: (type: NotificationType, message: string) => void;
  removeNotification: (id: string) => void;
  clearNotifications: () => void;
  unreadCount: number;
  hasUnread: boolean;
}

const NotificationContext = React.createContext<NotificationContextValue | null>(null);

export function NotificationProvider({ children }: { children: React.ReactNode }) {
  const [notifications, setNotifications] = React.useState<NotificationItem[]>([]);
  const [lastReadTime, setLastReadTime] = React.useState<number>(Date.now());

  const addNotification = React.useCallback((type: NotificationType, message: string) => {
    const id = `notif_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
    const newNotification: NotificationItem = { id, type, message, timestamp: Date.now() };
    setNotifications(prev => {
      const updated = [...prev, newNotification];
      if (updated.length > 50) {
        return updated.slice(-50);
      }
      return updated;
    });
  }, []);

  const removeNotification = React.useCallback((id: string) => {
    setNotifications(prev => prev.filter(n => n.id !== id));
  }, []);

  const clearNotifications = React.useCallback(() => {
    setNotifications([]);
    setLastReadTime(Date.now());
  }, []);

  const unreadCount = React.useMemo(() => {
    return notifications.filter(n => n.timestamp > lastReadTime).length;
  }, [notifications, lastReadTime]);

  const hasUnread = unreadCount > 0;

  const value: NotificationContextValue = {
    notifications,
    addNotification,
    removeNotification,
    clearNotifications,
    unreadCount,
    hasUnread,
  };

  return h(NotificationContext.Provider, { value }, children);
}

const h = React.createElement;

export function useNotification(): NotificationContextValue {
  const context = React.useContext(NotificationContext);
  if (!context) {
    throw new Error("useNotification must be used within NotificationProvider");
  }
  return context;
}