import { useMemo, useState } from 'react';

import SnackbarPortal, { SnackbarProps } from './Snackbar';
import { SnackbarContext } from './SnackbarContext';

export interface SnackbarProviderProps {
  timeout?: number;
  children?: React.ReactNode;
}

export default function SnackbarProvider({ timeout = 4500, children }: SnackbarProviderProps) {
  const [state, setState] = useState<Omit<SnackbarProps, 'timeout'>>({
    text: '',
    timestamp: 0,
  });
  const { action, text, theme, timestamp } = state;

  return (
    <SnackbarContext.Provider
      value={useMemo(
        () => ({
          createSnackbar: ({ action, text, theme }) => {
            setState({ action, text, theme, timestamp: Date.now() });
          },
        }),
        [],
      )}
    >
      <SnackbarPortal
        action={action}
        text={text}
        timestamp={timestamp}
        timeout={timeout}
        theme={theme}
      />
      {children}
    </SnackbarContext.Provider>
  );
}
