import React, {useMemo} from 'react';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {windowDimensions} from '@shared/constants';
import {SPACING} from '@shared/theme';

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

export interface BottomModalListProps<ItemT = unknown>
  extends BottomSheetFlatListProps<ItemT>,
    Omit<BottomModalRootProps, 'children'>,
    Omit<BottomModalHeaderProps, 'style'> {
  title?: string;
  onGoBack?: () => void;
  withBackdrop?: boolean;
  withHeader?: boolean;
}

export function BottomModalList<T extends object>({
  isVisible,
  onClose,
  snapPoints,
  footerComponent,
  filterable,
  title,
  onGoBack,
  enableDynamicSizing = true,
  fullScreen,
  withBackButton,
  withCloseButton,
  withBackdrop,
  withHeader = true,
  titleNumberOfLines,
  paddingBottom: paddingBottomProp,
  ...flatListProps
}: BottomModalListProps<T>) {
  const {top, bottom} = useSafeAreaInsets();
  const paddingBottom = (paddingBottomProp ?? bottom) + SPACING['x2.5'];

  /**
   * This is required to avoid overlaps on the phone's StatusBar
   */
  const safeSnapPoint = useMemo(
    () =>
      snapPoints?.map(e => (e === '100%' ? windowDimensions.height - top : e)),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [top],
  );

  return (
    <BottomModalRoot
      isVisible={isVisible}
      onClose={onClose}
      enableDynamicSizing={!snapPoints && enableDynamicSizing}
      snapPoints={safeSnapPoint}
      footerComponent={footerComponent}
      fullScreen={fullScreen}
      withBackdrop={withBackdrop}>
      {withHeader && (
        <BottomModalHeader
          title={title}
          onClose={onClose}
          onGoBack={onGoBack}
          style={styles.header}
          withBackButton={withBackButton}
          withCloseButton={withCloseButton}
          titleNumberOfLines={titleNumberOfLines}
        />
      )}
      <BottomSheetFlatList
        filterable={filterable}
        paddingBottom={paddingBottom}
        {...flatListProps}
      />
    </BottomModalRoot>
  );
}
