"use client";

import { createContext, ReactNode, useContext } from "react";
import { useRouter } from "next/navigation";

import { IFunnelPaymentPlacement } from "@/entities/session/funnel/types";
import { useMultiPageNavigation } from "@/hooks/multiPages/useMultiPageNavigation";
import { ROUTES } from "@/shared/constants/client-routes";

interface MultiPageNavigationContextType {
  navigation: ReturnType<
    typeof useMultiPageNavigation<IFunnelPaymentPlacement>
  >;
}

const MultiPageNavigationContext = createContext<
  MultiPageNavigationContextType | undefined
>(undefined);

interface MultiPageNavigationProviderProps {
  children: ReactNode;
  data: IFunnelPaymentPlacement[];
  currentType: string;
}

export function MultiPageNavigationProvider({
  children,
  data,
  currentType,
}: MultiPageNavigationProviderProps) {
  const router = useRouter();

  const navigation = useMultiPageNavigation<IFunnelPaymentPlacement>({
    data,
    currentType,
    getTypeFromItem: item => item.type ?? "",
    navigateToItemByType: type => {
      router.push(ROUTES.additionalPurchases(type));
    },
    onComplete: () => {
      router.push(ROUTES.home());
    },
  });

  return (
    <MultiPageNavigationContext.Provider value={{ navigation }}>
      {children}
    </MultiPageNavigationContext.Provider>
  );
}

export function useMultiPageNavigationContext() {
  const context = useContext(MultiPageNavigationContext);
  if (!context) {
    throw new Error(
      "useMultiPageNavigationContext must be used within MultiPageNavigationProvider"
    );
  }
  return context;
}
