"use client";
import {
  createContext,
  ReactNode,
  useContext,
  useEffect,
  useState
} from "react";
import toast from "react-hot-toast";

export interface Notification {
  id: string;
  type: "success" | "error" | "warning" | "info";
  title: string;
  message?: string;
  timestamp: Date;
  read: boolean;
}

interface NotificationContextType {
  notifications: Notification[];
  unreadCount: number;
  addNotification: (
    notification: Omit<Notification, "id" | "timestamp" | "read">
  ) => void;
  markAsRead: (id: string) => void;
  markAllAsRead: () => void;
  clearNotification: (id: string) => void;
  clearAll: () => void;
}

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

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

  const addNotification = (
    notification: Omit<Notification, "id" | "timestamp" | "read">
  ) => {
    const newNotification: Notification = {
      ...notification,
      id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
      timestamp: new Date(),
      read: false
    };
    setNotifications((prev) => [newNotification, ...prev]);
  };

  // Listen for WebSocket events and add notifications
  useEffect(() => {
    const handleFileUpdate = (event: CustomEvent) => {
      const data = event.detail;
      if (data.type === "add") {
        // New file detected and task created
        const notification = {
          type: "info" as const,
          title: "New File Detected",
          message: `File "${data.file}" in dataset "${data.dataset}" has been detected and queued for processing.`
        };
        addNotification(notification);
        toast.success(`New file detected: ${data.file}`, {
          duration: 5000
        });
      }
    };

    const handleTaskUpdate = (event: CustomEvent) => {
      const data = event.detail;
      // For now, we'll focus on file creation notifications
      // Task status updates can be added later if needed
      if (data.type === "created" || data.type === "started") {
        // This might be redundant with fileUpdate, but could be useful for manual task creation
        const notification = {
          type: "info" as const,
          title: "Task Created",
          message: `New processing task started for "${data.input}".`
        };
        addNotification(notification);
        toast.success(`Task started for: ${data.input}`, {
          duration: 5000
        });
      }
    };

    window.addEventListener("fileUpdate", handleFileUpdate as EventListener);
    window.addEventListener("taskUpdate", handleTaskUpdate as EventListener);

    return () => {
      window.removeEventListener(
        "fileUpdate",
        handleFileUpdate as EventListener
      );
      window.removeEventListener(
        "taskUpdate",
        handleTaskUpdate as EventListener
      );
    };
  }, [addNotification]);

  const markAsRead = (id: string) => {
    setNotifications((prev) =>
      prev.map((notif) => (notif.id === id ? { ...notif, read: true } : notif))
    );
  };

  const markAllAsRead = () => {
    setNotifications((prev) => prev.map((notif) => ({ ...notif, read: true })));
  };

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

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

  const unreadCount = notifications.filter((n) => !n.read).length;

  return (
    <NotificationContext.Provider
      value={{
        notifications,
        unreadCount,
        addNotification,
        markAsRead,
        markAllAsRead,
        clearNotification,
        clearAll
      }}
    >
      {children}
    </NotificationContext.Provider>
  );
}

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