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

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

/** Value of {@link AlertContext} */
export interface AlertContextValue {
  /** Visual {@link Alert} appearance */
  appearance: AlertAppearance;
  /** Function that should hide {@link Alert} */
  onDismiss?: () => void;
}

const AlertContext = createContext<AlertContextValue | undefined>(undefined);

/** Provider for alert data */
export function AlertContextProvider({
  appearance,
  onDismiss,
  children,
}: PropsWithChildren<AlertContextValue>) {
  const value: AlertContextValue = useMemo(() => ({ appearance, onDismiss }), [appearance, onDismiss]);

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

/** Returns data for alert */
export function useAlertContext(): AlertContextValue {
  const value = useContext(AlertContext);
  if (!value) {
    throw new Error('useAlertContext should be used only inside AlertContextProvider');
  }

  return value;
}
