/// <reference types="@applicaster/applicaster-types" />
import { useTheme } from "@applicaster/zapp-react-native-utils/theme";

import React, { useCallback, useEffect, useState } from "react";
import { Keyboard, StyleSheet, View } from "react-native";

import { Overlay } from "./Overlay";
import { ModalBottomSheetFrame } from "./ModalBottomSheetFrame";
import {
  useIsTablet,
  useNavigation,
} from "@applicaster/zapp-react-native-utils/reactHooks";
import { useDimensions } from "@applicaster/zapp-react-native-utils/reactHooks/layout";
import { ModalComponent } from "@applicaster/zapp-react-native-ui-components/Components";

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "flex-end",
  },
});

type Props = {
  ModalBottomSheetContent:
    | React.FC<ModalBottomSheetContentProps>
    | React.ComponentClass<ModalBottomSheetContentProps>;
  modalBottomSheetContentProps: Record<string, any>;
};

export function ModalBottomSheet(props: Props) {
  const theme = useTheme<BaseThemePropertiesMobile>();
  const navigator = useNavigation();
  const dimensions = useDimensions();
  const [visible, setVisible] = useState(true);

  const {
    modal_bottom_sheet_background_color: sheetBackgroundColor,
    modal_bottom_sheet_overlay_color: sheetOverlayColor,
    modal_bottom_sheet_top_corner_radius: sheetCornerRadius,
    modal_bottom_sheet_handle: sheetHandleEnabled,
    modal_bottom_sheet_handle_color: sheetHandleColor,
    modal_bottom_sheet_handle_focus_color: sheetHandleFocusedColor,
    modal_bottom_sheet_tablet_max_width: sheetTabletMaxWidth,
  } = theme;

  const sheetMaxHeight = dimensions.height * 0.75; // Set a default max height

  const {
    ModalBottomSheetContent = ModalComponent,
    modalBottomSheetContentProps,
  } = props;

  useEffect(() => {
    Keyboard.dismiss();
  }, []);

  const dismiss = useCallback(() => setVisible(false), []);

  const isTablet = useIsTablet();

  const maxWidth = isTablet ? sheetTabletMaxWidth : dimensions.width;

  return (
    <View style={styles.container}>
      <Overlay
        visible={visible}
        overlayColor={sheetOverlayColor}
        closeToast={dismiss}
      />
      <ModalBottomSheetFrame
        backgroundColor={sheetBackgroundColor}
        cornerRadius={sheetCornerRadius}
        maxHeight={sheetMaxHeight}
        maxWidth={maxWidth}
        dimensions={dimensions}
        visible={visible}
        closeToast={dismiss}
        handleProps={{
          enabled: sheetHandleEnabled,
          color: sheetHandleColor,
          focusedColor: sheetHandleFocusedColor,
        }}
      >
        <ModalBottomSheetContent
          width={
            Math.min(sheetTabletMaxWidth, dimensions.width) || dimensions.width
          }
          maxHeight={sheetMaxHeight}
          {...modalBottomSheetContentProps}
          dismiss={dismiss}
          currentRoute={navigator.currentRoute}
        />
      </ModalBottomSheetFrame>
    </View>
  );
}
