import * as React from "react";

import { ModalPresenter } from "./ModalPresenter";
import { ModalContent } from "./ModalContent";
import { ModalChildrenWrapper } from "./ModalChildrenWrapper";
import { PathnameContext } from "@applicaster/zapp-react-native-ui-components/Contexts/PathnameContext";
import { ScreenContextProvider } from "@applicaster/zapp-react-native-ui-components/Contexts/ScreenContext";
import { ROUTE_TYPES } from "@applicaster/zapp-react-native-utils/navigationUtils/routeTypes";
import { useModalStoreState } from "@applicaster/zapp-react-native-utils/modalState";

export function ModalProvider() {
  const modalState = useModalStoreState();

  const [modalVisible, setModalVisible] = React.useState(false);
  const [modalShown, setModalShown] = React.useState(false);

  React.useEffect(() => {
    setModalVisible(!!modalState);

    if (!modalState && modalShown) {
      setModalShown(false);
    }
  }, [modalState]);

  if (!modalState?.screen) {
    return null;
  }

  const modalScreenProps = {
    screenData: modalState?.screen,
    screenId: modalState?.screen?.id,
    screenType: "river",
    ...modalState.props,
  };

  const pathname = `${ROUTE_TYPES.MODAL}/${modalScreenProps?.screenId}`;

  const shouldShowModal = modalVisible && modalState?.visible;

  return (
    <PathnameContext.Provider value={pathname}>
      <ScreenContextProvider pathname={pathname}>
        <ModalPresenter
          visible={shouldShowModal}
          {...modalState?.options}
          statusBarTranslucent
        >
          <ModalChildrenWrapper>
            <ModalContent modalScreenProps={modalScreenProps} />
          </ModalChildrenWrapper>
        </ModalPresenter>
      </ScreenContextProvider>
    </PathnameContext.Provider>
  );
}
