import { useRef, useState } from 'react';

import type { BoxProps } from '~/src/components/Box';
import type { ReactNode } from 'react';

import Box from '~/src/components/Box';
import Clickable from '~/src/components/Clickable';
import CaretIcon from '~/src/components/Icon/CaretIcon';
import Text from '~/src/components/Text';
import wait from '~/src/lib/utils/wait';

export const CollapsableSection = ({
  title,
  testId,
  children,
  scrollMarginTop,
  ...boxProps
}: {
  title: string;
  testId?: string;
  children: ReactNode;
  scrollMarginTop?: string;
} & BoxProps) => {
  const [isExpanded, setIsExpanded] = useState(false);
  const contentNodeRef = useRef<HTMLDivElement>(null);

  return (
    <Box {...boxProps}>
      <Clickable
        testId={testId}
        onClick={async () => {
          setIsExpanded(!isExpanded);

          await wait(200);
          contentNodeRef.current?.scrollIntoView({ behavior: 'smooth' });
        }}
        width="auto"
      >
        <Text flexRow isBold alignCenter gap=".6rem" size="1.5rem">
          {title} <CaretIcon size={12} direction={isExpanded ? 'up' : 'down'} />
        </Text>
      </Clickable>
      <Box
        nodeRef={contentNodeRef}
        style={{
          display: isExpanded ? 'block' : 'none',
          scrollMarginTop,
        }}
        margin="2.2rem 0 0"
      >
        {children}
      </Box>
    </Box>
  );
};
