import React from "react";
import { LayoutChangeEvent, Platform, StyleSheet, View } from "react-native";

import { Handle, HandleProps } from "./Handle";
import { DraggableBottomSheet } from "./DraggableBottomSheet";
import {
  SafeAreaView,
  useSafeAreaFrame,
  useSafeAreaInsets,
} from "react-native-safe-area-context";
import {
  isAndroidPlatform,
  isAndroidVersionAtLeast,
  platformSelect,
} from "@applicaster/zapp-react-native-utils/reactUtils";

type Props = {
  children: React.ReactChild;
  backgroundColor: string;
  cornerRadius: number;
  maxHeight: number;
  maxWidth: number;
  visible: boolean;
  handleProps: HandleProps;
  closeToast: () => void;
  dimensions: {
    statusBarHeight: any;
    width: number;
    height: number;
  };
};

const styles = StyleSheet.create({
  toastFrameContainer: {
    width: "100%",
    alignSelf: "center",
  },
});

const defaultBottomOffset = platformSelect({
  ios: 34,
  android: 0,
});

const SAFE_AREA_BREAKING_API_VERSION = 35;

const getSheetHeight = ({ height, bottomOffset, maxHeight }) => {
  return platformSelect({
    ios: height - bottomOffset,
    default:
      (height || maxHeight) -
      (isAndroidPlatform() &&
      !isAndroidVersionAtLeast(SAFE_AREA_BREAKING_API_VERSION)
        ? bottomOffset
        : 0),
  });
};

const useGetSheetHeight = (height, maxHeight) => {
  const { bottom = defaultBottomOffset } = useSafeAreaInsets();

  const bottomOffset = bottom;

  return getSheetHeight({
    height,
    bottomOffset,
    maxHeight,
  });
};

export function ModalBottomSheetFrame(props: Props) {
  const {
    children,
    backgroundColor,
    cornerRadius,
    maxHeight,
    maxWidth,
    visible,
    handleProps,
    dimensions,
  } = props;

  const safeAreaDims = useSafeAreaFrame();

  const extraStyles = {
    backgroundColor,
    borderTopLeftRadius: cornerRadius,
    borderTopRightRadius: cornerRadius,
    maxHeight,
    maxWidth: Math.min(Number(maxWidth), safeAreaDims.width),
  };

  const [height, setHeight] = React.useState(0);

  const onLayout = (event: LayoutChangeEvent) => {
    const { height } = event.nativeEvent.layout;

    if (height !== 0) {
      setHeight(height);
    }
  };

  const { bottom = defaultBottomOffset } = useSafeAreaInsets();

  const sheetHeight = useGetSheetHeight(height, maxHeight);

  return (
    <DraggableBottomSheet
      sheetHeight={sheetHeight}
      visible={height > 0 && visible}
      dismiss={props.closeToast}
      hasHeader={handleProps.enabled}
      header={(dragging) => <Handle {...handleProps} focused={dragging} />}
      maxWidth={maxWidth}
      {...dimensions}
      height={safeAreaDims.height - (Platform.OS === "ios" ? bottom : 0)}
    >
      <SafeAreaView
        edges={["left", "right", "bottom"]}
        style={[styles.toastFrameContainer, extraStyles]}
      >
        <View onLayout={onLayout}>{children}</View>
      </SafeAreaView>
    </DraggableBottomSheet>
  );
}
