import React, { createContext, useContext, useState, ReactNode } from "react";
import { NotificationData } from "@/types";
import { generateId } from "@/lib/utils";
import { toast } from "@/hooks/use-toast";

interface NotificationContextType {
  notifications: NotificationData[];
  showNotification: (notification: Omit<NotificationData, "id">) => void;
  removeNotification: (id: string) => void;
  clearAll: () => void;
}

const NotificationContext = createContext<NotificationContextType | undefined>(
  undefined
);

export function NotificationProvider({ children }: { children: ReactNode }) {
  const [notifications, setNotifications] = useState<NotificationData[]>([]);

  const showNotification = (notification: Omit<NotificationData, "id">) => {
    const id = generateId();
    const newNotification: NotificationData = { ...notification, id };

    setNotifications((prev) => [...prev, newNotification]);

    // Use shadcn toast with proper variants based on type
    const getToastVariant = (type: string) => {
      switch (type) {
        case "success":
          return "success" as const;
        case "error":
          return "destructive" as const;
        case "warning":
          return "warning" as const;
        case "info":
          return "info" as const;
        default:
          return "default" as const;
      }
    };

    const variant = getToastVariant(notification.type);

    toast({
      title: notification.title,
      description: notification.message,
      variant,
      duration: notification.duration || 5000,
    });

    // Auto-remove after duration
    if (notification.duration !== 0) {
      setTimeout(() => {
        removeNotification(id);
      }, notification.duration || 5000);
    }
  };

  const removeNotification = (id: string) => {
    setNotifications((prev) => prev.filter((n) => n.id !== id));
  };

  const clearAll = () => {
    setNotifications([]);
  };

  return (
    <NotificationContext.Provider
      value={{
        notifications,
        showNotification,
        removeNotification,
        clearAll,
      }}
    >
      {children}
    </NotificationContext.Provider>
  );
}

export function useNotification() {
  const context = useContext(NotificationContext);
  if (context === undefined) {
    throw new Error(
      "useNotification must be used within a NotificationProvider"
    );
  }
  return context;
}
