import React, {
  createContext,
  useContext,
  useState,
  ReactNode,
  useMemo,
} from "react";

export interface NavigationState {
  currentSection: string;
  breadcrumbs: BreadcrumbItem[];
  notifications: NotificationItem[];
}

export interface BreadcrumbItem {
  label: string;
  path?: string;
  active?: boolean;
}

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

interface NavigationActions {
  setCurrentSection: (section: string) => void;
  setBreadcrumbs: (breadcrumbs: BreadcrumbItem[]) => void;
  addNotification: (
    notification: Omit<NotificationItem, "id" | "timestamp" | "read">
  ) => void;
  markNotificationRead: (id: string) => void;
  clearAllNotifications: () => void;
}

interface NavigationContextType {
  state: NavigationState;
  actions: NavigationActions;
}

const NavigationContext = createContext<NavigationContextType | undefined>(
  undefined
);

export function NavigationProvider({ children }: { children: ReactNode }) {
  const [state, setState] = useState<NavigationState>({
    currentSection: "traces",
    breadcrumbs: [{ label: "AgentGraph", active: true }],
    notifications: [],
  });

  const actions: NavigationActions = useMemo(
    () => ({
      setCurrentSection: (section: string) => {
        setState((prev) => ({ ...prev, currentSection: section }));
      },

      setBreadcrumbs: (breadcrumbs: BreadcrumbItem[]) => {
        setState((prev) => ({ ...prev, breadcrumbs }));
      },

      addNotification: (notification) => {
        const newNotification: NotificationItem = {
          ...notification,
          id: Date.now().toString(),
          timestamp: new Date(),
          read: false,
        };
        setState((prev) => ({
          ...prev,
          notifications: [newNotification, ...prev.notifications],
        }));
      },

      markNotificationRead: (id: string) => {
        setState((prev) => ({
          ...prev,
          notifications: prev.notifications.map((n) =>
            n.id === id ? { ...n, read: true } : n
          ),
        }));
      },

      clearAllNotifications: () => {
        setState((prev) => ({ ...prev, notifications: [] }));
      },
    }),
    []
  );

  return (
    <NavigationContext.Provider value={{ state, actions }}>
      {children}
    </NavigationContext.Provider>
  );
}

export function useNavigation() {
  const context = useContext(NavigationContext);
  if (context === undefined) {
    throw new Error("useNavigation must be used within a NavigationProvider");
  }
  return context;
}
