import type { ReactElement } from 'react';
import React, { useContext, useCallback, forwardRef } from 'react';
import type {
  NativeScrollEvent,
  NativeSyntheticEvent,
  ScrollViewProps,
} from 'react-native';
import { ScrollView } from 'react-native';
import type { BottomSheetContextType } from './BottomSheetContext';
import BottomSheetContext from './BottomSheetContext';

const BottomSheetScrollView = forwardRef<ScrollView, ScrollViewProps>(
  ({ scrollEventThrottle = 100, ...props }, ref): ReactElement => {
    const { setInternalShowDivider } =
      useContext<BottomSheetContextType>(BottomSheetContext);

    const onScrollBeginDrag = useCallback(
      (e: NativeSyntheticEvent<NativeScrollEvent>) => {
        setInternalShowDivider(true);

        props?.onScrollBeginDrag?.(e);
      },
      []
    );

    const onMomentumScrollBegin = useCallback(
      (e: NativeSyntheticEvent<NativeScrollEvent>) => {
        setInternalShowDivider(true);

        props?.onMomentumScrollEnd?.(e);
      },
      []
    );

    const onMomentumScrollEnd = useCallback(
      (e: NativeSyntheticEvent<NativeScrollEvent>) => {
        setInternalShowDivider(false);

        props?.onMomentumScrollEnd?.(e);
      },
      []
    );

    return (
      <ScrollView
        {...props}
        ref={ref}
        onScrollBeginDrag={onScrollBeginDrag}
        onMomentumScrollBegin={onMomentumScrollBegin}
        onMomentumScrollEnd={onMomentumScrollEnd}
        scrollEventThrottle={scrollEventThrottle}
      />
    );
  }
);

export default BottomSheetScrollView;
