import React, {
  forwardRef,
  RefObject,
  useEffect,
  useCallback,
  useMemo,
  ForwardedRef,
} from 'react';
import {Keyboard, StatusBar, View} from 'react-native';
import {GestureHandlerRootView} from 'react-native-gesture-handler';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {useSharedValue} from 'react-native-reanimated';
import {ContainerLayoutState} from '@gorhom/bottom-sheet/lib/typescript/types';
import GorhomBottomSheet, {
  BottomSheetHandle,
  BottomSheetScrollView,
} from '@gorhom/bottom-sheet';
import {useKeyboard} from '@hooks/useKeyboard';
import {useBackHandler} from '@hooks/useBackHandler';
import {windowDimensions} from '@shared/constants';
import {useTheme} from '@shared/theme';

import BottomSheetBackdrop from './BottomSheetBackdrop';
import BottomSheetFooter from './BottomSheetFooter';
import {BottomSheetProps} from './interfaces';
import {getMaxSnapPoint} from './utils';
import {styles} from './styles';

const DEFAULT_SNAP_POINTS = ['50%', '70%'];
const STATUS_BAR_HEIGHT = StatusBar.currentHeight || 0;

function BottomSheetComponent(
  {
    show,
    locked,
    onClose,
    children,
    extraFooterOffset,
    handleStyle,
    backgroundStyle,
    headerComponent: HeaderComponent,
    enableContentPanningGesture = false,
    enableOverDrag = false,
    snapPoints = DEFAULT_SNAP_POINTS,
    showFooter = true,
    enableDynamicSizing,
    ...props
  }: BottomSheetProps,
  ref: ForwardedRef<GorhomBottomSheet>,
) {
  const {theme} = useTheme();
  const {top} = useSafeAreaInsets();
  const maxDynamicContentSize =
    windowDimensions.height - top - STATUS_BAR_HEIGHT;
  const maxSnapPoint = useMemo(() => getMaxSnapPoint(snapPoints), [snapPoints]);

  const handleClose = useCallback(() => {
    (ref as RefObject<GorhomBottomSheet>)?.current?.close();
    onClose?.();
  }, [ref, onClose]);

  const handleExpandBottomSheet = useCallback(() => {
    (ref as RefObject<GorhomBottomSheet>)?.current?.snapToIndex(1);
  }, [ref]);
  useKeyboard({onShow: handleExpandBottomSheet, dependency: show}, true);

  const goBack = useCallback(() => {
    if (show && !locked) {
      onClose?.();
      return true;
    }
  }, [locked, onClose, show]);

  useBackHandler(goBack);

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

  const containerLayoutState = useSharedValue<ContainerLayoutState>({
    height: windowDimensions.height,
    offset: {
      top: 0,
      bottom: 0,
      left: 0,
      right: 0,
    },
  });

  return (
    <View pointerEvents={show ? undefined : 'none'} style={styles.container}>
      <GestureHandlerRootView style={styles.fill}>
        <GorhomBottomSheet
          detached
          enableDynamicSizing={enableDynamicSizing}
          maxDynamicContentSize={maxDynamicContentSize}
          enablePanDownToClose={!locked}
          index={-1}
          handleIndicatorStyle={[
            styles.body,
            {backgroundColor: theme.neutralBgSecondary},
          ]}
          containerLayoutState={containerLayoutState}
          snapPoints={enableDynamicSizing ? undefined : snapPoints}
          enableOverDrag={enableOverDrag}
          enableContentPanningGesture={enableContentPanningGesture}
          handleStyle={[styles.handle, handleStyle]}
          handleComponent={handleProps => (
            <>
              <BottomSheetHandle {...handleProps} />
              {!!HeaderComponent && <HeaderComponent />}
            </>
          )}
          backdropComponent={backdropProps => (
            <BottomSheetBackdrop
              {...backdropProps}
              {...(!locked && {onClose})}
              show={show}
            />
          )}
          {...(showFooter && {
            footerComponent: footerProps => (
              <BottomSheetFooter
                maxSnapPoint={maxSnapPoint}
                extraOffset={extraFooterOffset}
                {...footerProps}
              />
            ),
          })}
          backgroundStyle={[
            styles.background,
            {backgroundColor: theme.background.layout.tertiary},
            backgroundStyle,
          ]}
          ref={ref}
          onClose={handleClose}
          {...props}>
          {enableDynamicSizing ? (
            <BottomSheetScrollView scrollEnabled={false}>
              {children}
            </BottomSheetScrollView>
          ) : (
            children
          )}
        </GorhomBottomSheet>
      </GestureHandlerRootView>
    </View>
  );
}

export type BottomSheetType = GorhomBottomSheet;

/**
 * @deprecated Use `_HuGo/Modals` instead
 */
export const BottomSheet = forwardRef(BottomSheetComponent);
