import React, { useImperativeHandle, useState, useRef } from "react";
import { View, TouchableOpacity, ScrollView } from "react-native";
import { Portal } from "@gorhom/portal";
import { Motion } from "@legendapp/motion";

import { Palette } from "../../styles";
import {
  isDesktop,
  isLargeDesktop,
  sidebarWidth,
} from "../../hooks/useLayoutType";

export const SheetScrollView = ScrollView;
export const SheetBackdrop = View;

const BottomSheet = React.forwardRef((props, ref) => {
  const [showSheet, setShowSheet] = useState(false);

  const bottomSheetRef = useRef();

  useImperativeHandle(ref, () => ({
    snapToIndex: () => {
      setShowSheet(true);
    },
    expand: () => {
      setShowSheet(true);
    },
    collapse: () => closeBottomSheet(),
    close: () => closeBottomSheet(),
  }));

  const closeBottomSheet = () => {
    setShowSheet(false);
    props.onChange(-1);
  };

  if (!showSheet) {
    return null;
  }

  return (
    <Portal>
      <Motion.View
        initial={{ right: -500, opacity: 0 }}
        animate={{ right: 0, opacity: 1 }}
        style={{
          position: "fixed",
          right: 0,
          top: 0,
          left: 0,
          bottom: 0,
          flex: 1,
          zIndex: 1000000,
          justifyContent: "center",
          alignItems: "center",
        }}
      >
        <TouchableOpacity
          onPress={closeBottomSheet}
          ref={bottomSheetRef}
          style={{
            position: "absolute",
            right: 0,
            top: 0,
            left: 0,
            bottom: 0,
            flex: 1,
            backgroundColor: "rgba(0,0,0,0.4)",
          }}
        />

        <View
          style={{
            position: "absolute",
            top: 0,
            right: 0,
            bottom: 0,
            height: "100%",
            width: isDesktop
              ? sidebarWidth * (isLargeDesktop ? 2 : 1.5)
              : "100%",
            backgroundColor: Palette.lightPurple,
            overflow: "scroll",
          }}
        >
          {props.children}
        </View>
      </Motion.View>
    </Portal>
  );
});
// TODO une croix pour fermer sur mobile web

export default BottomSheet;
