import React, { useEffect, useRef } from 'react';
import { Box } from '@nova-hf/ui';
import { gsap } from 'gsap';

type InputWrapperProps = {
  input: React.ReactNode;
  slideActive: boolean | undefined;
  slideComponent: React.ReactNode;
};

const InputWrapper = ({ slideActive, input, slideComponent }: InputWrapperProps) => {
  const slideComponentRef = useRef<HTMLDivElement>(null);
  const wrapperRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const wrapper = wrapperRef.current;
    const input = inputRef.current;
    const slide = slideComponentRef.current;

    if (!wrapper || !input || !slide || slideActive === undefined) return;

    const inputHeight = input.getBoundingClientRect().height;
    const slideHeight = slide.getBoundingClientRect().height;

    const totalHeight = slideActive ? inputHeight + slideHeight + 16 : inputHeight;

    const tl = gsap.timeline();

    tl.to(wrapper, {
      height: totalHeight,
      duration: 0.3,
      ease: 'power2.out',
    });

    tl.to(
      slide,
      {
        opacity: slideActive ? 1 : 0,
        duration: 0.2,
        ease: 'power2.out',
      },
      '<',
    );
  }, [slideActive]);

  return (
    <Box
      ref={wrapperRef}
      display="flex"
      flexDirection="column"
      justifyContent="flex-start"
      width="100%"
      style={{ overflow: 'hidden', height: 'auto' }}
    >
      <Box ref={inputRef} display="flex" marginBottom={2}>
        {input}
      </Box>
      <Box
        ref={slideComponentRef}
        display="flex"
        style={{
          opacity: 0,
          transition: 'opacity 0.2s ease',
          whiteSpace: 'pre-wrap',
          wordBreak: 'break-word',
          width: '100%',
          paddingBottom: 2,
        }}
      >
        {slideComponent}
      </Box>
    </Box>
  );
};

export default InputWrapper;
