import Box from '@mui/material/Box';
import { SxProps, Theme } from '@mui/material';
import { RefObject, useRef } from 'react';
import { useAutoScrollToBottom } from '../hooks/useAutoScrollToBottom';

interface ScrollableProps {
  children?: React.ReactNode;
  sx?: SxProps<Theme>;
  autoscroll?: boolean;
  textFieldRef?: RefObject<HTMLElement | null>; // Reference to the element that triggers auto-scroll
  fallbackThreshold?: number;
  contentUpdateTrigger?: any;
  className?: string;
}

const Scrollable = (props: ScrollableProps) => {
  const { sx, className, children, autoscroll, textFieldRef, fallbackThreshold = 0.33, contentUpdateTrigger } = props;  
  // Create a default ref if textFieldRef is not provided
  const defaultTextFieldRef = useRef<HTMLElement | null>(null);
  const scrollRef = useAutoScrollToBottom(textFieldRef ?? defaultTextFieldRef, true, fallbackThreshold, contentUpdateTrigger);

  return (
    <Box
      className={`Scrollable ${className || ""}`}
      sx={{
        display: 'flex',
        flexDirection: 'column',
        margin: '0 auto',
        p: 0,
        flexGrow: 1,
        overflow: 'auto',
        // backgroundColor: '#F5F5F5',
        ...sx,
      }}
      ref={autoscroll !== undefined && autoscroll !== false ? scrollRef : undefined}
    >
      {children}
    </Box>
  );
};

export { useAutoScrollToBottom, Scrollable };