import React, { useEffect, useRef, useState, useMemo } from 'react';
import { View } from 'react-native';

import type { ReactNode } from 'react';
import ToastContainer from './ToastContainer';
import {
  ToastConfigContext,
  ToastContext,
  fallbackToastControlContext,
} from './ToastContext';
import type { ToastControllerContextType } from './ToastContext';
import type { ToastContainerProps } from './types';
import { useDeprecation } from '../../utils/hooks';

type ToastProviderProps = {
  /**
   * Content to be wrapped.
   */
  children?: ReactNode;
} & ToastContainerProps;

const ToastProvider = ({
  children,
  displayType = 'single',
  position: _position,
}: ToastProviderProps) => {
  const position: ToastContainerProps['position'] =
    _position === undefined ? 'bottom' : _position;

  useDeprecation(
    "Toast's position prop is deprecated and will be removed in the next major release.\nPlease remove it.",
    _position !== undefined
  );

  const toastRef = useRef<ToastControllerContextType>(null);
  const [refState, setRefState] = useState<ToastControllerContextType>();

  useEffect(() => {
    if (toastRef.current) {
      setRefState(toastRef.current);
    }
  }, []);

  const config = useMemo(
    () => ({ displayType, position }),
    [displayType, position]
  );

  return (
    <ToastContext.Provider value={refState || fallbackToastControlContext}>
      <View style={{ flex: 1 }}>
        {refState ? children : null}
        <ToastConfigContext.Provider value={config}>
          <ToastContainer
            ref={toastRef}
            displayType={displayType}
            position={position}
          />
        </ToastConfigContext.Provider>
      </View>
    </ToastContext.Provider>
  );
};

export default ToastProvider;
