import { AnimatePresence, Motion } from "@legendapp/motion";
import { useKeyboard } from "@react-native-community/hooks";
import React, { useCallback, useEffect, useState } from "react";
import { Keyboard, StyleSheet } from "react-native";

import BottomSheet from "./BottomSheet";

import useLayoutType from "../hooks/useLayoutType";
import { Palette } from "../styles";

export default ({
  children,
  bottomSheetRef,
  snapPoints = ["25%", "50%"],
  handleStyle = {},
  ...rest
}) => {
  const [currentSnapPointIndex, setCurrentSnapPointIndex] = useState(0);

  const { keyboardShown = false } = useKeyboard();
  const { isWeb } = useLayoutType();

  const handleSheetChanges = useCallback((index) => {
    setCurrentSnapPointIndex(index);

    if (index <= 0) {
      Keyboard.dismiss();
    }
  }, []);

  useEffect(() => {
    if (bottomSheetRef.current && !isWeb && currentSnapPointIndex > 0) {
      if (keyboardShown) {
        bottomSheetRef.current.expand();
      } else {
        bottomSheetRef.current.snapToIndex(1);
      }
    }
  }, [keyboardShown]);

  return (
    <>
      <AnimatePresence>
        {currentSnapPointIndex > 0 ? (
          <Motion.Pressable
            style={{ ...StyleSheet.absoluteFill }}
            onPress={() => bottomSheetRef?.current?.close()}
          >
            <Motion.View
              key={"A"}
              style={{
                flex: 1,
                backgroundColor: Palette.black,
              }}
              initial={{ opacity: 0 }}
              animate={{ opacity: 0.9 }}
              exit={{ opacity: 0 }}
              transition={{
                default: {
                  type: "spring",
                },
                opacity: {
                  type: "timing",
                },
              }}
            ></Motion.View>
          </Motion.Pressable>
        ) : null}
      </AnimatePresence>

      <BottomSheet
        ref={bottomSheetRef}
        snapPoints={snapPoints}
        handleStyle={{
          backgroundColor: Palette.darkPurple,
          ...handleStyle,
        }}
        handleIndicatorStyle={{ backgroundColor: Palette.primary }}
        style={{ zIndex: 100 }}
        onChange={handleSheetChanges}
        {...rest}
      >
        {children}
      </BottomSheet>
    </>
  );
};
