import { PropsWithChildren, createContext, useContext, useMemo } from 'react';

import { ToastAppearance } from '../constants';

/** Value of {@link ToastContext} */
export interface ToastContextValue {
  /** Visual {@link Toast} appearance */
  appearance: ToastAppearance;
  /** Function that should hide {@link Toast} */
  onDismiss?: () => void;
}

const ToastContext = createContext<ToastContextValue | undefined>(undefined);

/** Provider for {@link Toast} data */
export function ToastContextProvider({
  appearance,
  onDismiss,
  children,
}: PropsWithChildren<ToastContextValue>) {
  const value: ToastContextValue = useMemo(
    () => ({
      appearance,
      onDismiss,
    }),
    [appearance, onDismiss],
  );

  return <ToastContext.Provider value={value}>{children}</ToastContext.Provider>;
}

/** Returns data for {@link Toast} */
export function useToastContext(): ToastContextValue {
  const value = useContext(ToastContext);
  if (!value) {
    throw new Error('useToastContext should be used only inside ToastContextProvider');
  }

  return value;
}
