import React from "react";
import { Platform, Pressable, StyleSheet } from "react-native";
import { AnimatePresence, Motion } from "@legendapp/motion";
import { BlurView } from "expo-blur";
import { Portal } from "@gorhom/portal";

import useLayoutType from "../hooks/useLayoutType";

import { Palette, Style } from "../styles";
import { defaultBlurIntensity } from "../styles/Style";

const Overlay = ({
  isVisible,
  setIsVisible,

  blurIntensity = null,

  children,
  contentContainerStyle = {},

  hasPortal = true,
}) => {
  const { isNative } = useLayoutType();

  const ContentContainerView = hasPortal ? Portal : React.Fragment;

  return (
    <ContentContainerView>
      <AnimatePresence>
        {isVisible ? (
          <Motion.View
            key="overlay"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{
              type: "tween",
              duration: 500,
            }}
            style={{
              position: isNative ? "absolute" : "fixed",
              ...StyleSheet.absoluteFillObject,
              backgroundColor: Palette.ultraLightBlack,
              flex: 1,
              ...Style.containerCenter,
            }}
          >
            <BlurView
              intensity={blurIntensity || isNative ? defaultBlurIntensity : 15}
              tint="dark"
              style={{
                width: "100%",
                height: "100%",
                ...Style.containerCenter,
                ...StyleSheet.absoluteFillObject,
                ...contentContainerStyle,
              }}
              experimentalBlurMethod={
                Platform.OS !== "ios" ? "dimezisBlurView" : "none"
              }
            >
              <Pressable
                style={{
                  ...StyleSheet.absoluteFillObject,
                }}
                onPress={() => {
                  console.log("overlay pressed");
                  setIsVisible?.(false);
                }}
              />
              {children}
            </BlurView>
          </Motion.View>
        ) : null}
      </AnimatePresence>
    </ContentContainerView>
  );
};

export default Overlay;
