import React, {useCallback, useMemo, useState} from 'react';
import {LayoutChangeEvent, View} from 'react-native';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {MODAL_SPACING} from '@components/Modals/constants';
import {windowDimensions} from '@shared/constants';
import {COLORS} from '@shared/colors';
import {SPACING} from '@shared/theme';

import {BottomModalRoot, BottomModalRootProps} from '../BottomModalRoot';
import {
  BottomSheetFlatList,
  BottomSheetFlatListProps,
} from '../BottomSheetFlatList';

interface BottomModalListProps<ItemT = unknown>
  extends BottomSheetFlatListProps<ItemT>,
    Omit<BottomModalRootProps, 'children'> {}

/**
 * @deprecated Use `_HuGo/Modals` instead
 */
export function BottomModalList<T extends object>({
  isVisible,
  onClose,
  snapPoints,
  footerComponent,
  filterable,
  enableDynamicSizing = true,
  ...flatListProps
}: BottomModalListProps<T>) {
  const [footerHeight, setFooterHeight] = useState(0);
  const {top, bottom} = useSafeAreaInsets();
  const paddingBottom = (bottom || SPACING.x2) + MODAL_SPACING.modalSafeArea;

  /**
   * This is required to avoid overlaps on the phone's StatusBar
   */
  const safeSnapPoint = useMemo(() => [windowDimensions.height - top], [top]);

  const onModalClose = useCallback(() => {
    onClose();
    // setFilter('');
  }, [onClose]);

  const onFooterLayout = useCallback(
    (event: LayoutChangeEvent) =>
      setFooterHeight(event.nativeEvent.layout.height),
    [],
  );

  const customFooterComponent = footerComponent ? (
    <View
      onLayout={onFooterLayout}
      style={{paddingBottom, backgroundColor: COLORS.WHITE}}>
      {footerComponent}
    </View>
  ) : null;

  return (
    <BottomModalRoot
      isVisible={isVisible}
      onClose={onModalClose}
      enableDynamicSizing={!filterable && !snapPoints && enableDynamicSizing}
      snapPoints={filterable ? safeSnapPoint : snapPoints}
      footerComponent={customFooterComponent}>
      <BottomSheetFlatList
        filterable={filterable}
        paddingBottom={footerComponent ? footerHeight : paddingBottom}
        {...flatListProps}
      />
    </BottomModalRoot>
  );
}
