import React, {ReactNode, useCallback, useState} from 'react';
import {LayoutChangeEvent, StyleProp, View, ViewStyle} from 'react-native';
import {BottomSheetScrollView, BottomSheetView} from '@gorhom/bottom-sheet';
import {MODAL_SPACING} from '@components/Modals/constants';
import {useSafeAreaBottomPadding} from '@hooks/useSafeAreaBottomPadding';

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

export interface BottomModalProps extends BottomModalRootProps {
  title?: string;
  scrollable?: boolean;
  showCloseIcon?: boolean;
  HeaderComponent?: ReactNode;
  contentContainerStyle?: StyleProp<ViewStyle>;
  headerStyle?: StyleProp<ViewStyle>;
}

/**
 * @deprecated Use `_HuGo/Modals` instead
 */
export function BottomModal({
  children,
  title,
  footerComponent,
  onClose,
  showCloseIcon = false,
  scrollable = false,
  HeaderComponent,
  contentContainerStyle,
  headerStyle,
  ...props
}: BottomModalProps) {
  const paddingBottom = useSafeAreaBottomPadding({
    extra: MODAL_SPACING.modalSafeArea,
  });
  const [footerHeight, setFooterHeight] = useState(0);

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

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

  const headerContent = HeaderComponent || (
    <BottomModalHeader
      title={title}
      showCloseIcon={showCloseIcon}
      onClose={onClose}
      style={[styles.header, headerStyle]}
    />
  );

  const contentStyles = [
    styles.content,
    {paddingBottom: footerHeight || paddingBottom},
    contentContainerStyle,
  ];

  return (
    <BottomModalRoot
      footerComponent={customFooterComponent}
      onClose={onClose}
      {...props}>
      {scrollable ? (
        <BottomSheetScrollView contentContainerStyle={contentStyles}>
          {headerContent}
          {children}
        </BottomSheetScrollView>
      ) : (
        <BottomSheetView style={contentStyles}>
          {headerContent}
          {children}
        </BottomSheetView>
      )}
    </BottomModalRoot>
  );
}
