import React, { useCallback, useEffect, useRef } from 'react';

import { Container as ContainerComponent, ContainerRef } from '@cleartrip/ct-design-container';

import { IAnimatedComponentProps } from '../type';

const BaseContainer = ({ children, animated, styleConfig = {}, onTransitionEnd }: IAnimatedComponentProps) => {
  const { root: rootStyles = [] } = styleConfig || {};
  const containerRef = useRef<ContainerRef>(null);
  const transitionHandledRef = useRef(false);

  useEffect(() => {
    const elementRef = containerRef.current?.getElementRef();

    animated?.setWebElementRef?.(elementRef ?? null);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [containerRef]);

  const handleTransitionEnd = useCallback(() => {
    if (!transitionHandledRef.current) {
      transitionHandledRef.current = true;
      onTransitionEnd?.();
    }
  }, [onTransitionEnd]);

  return (
    <ContainerComponent
      ref={containerRef}
      // @ts-ignore
      styleConfig={{ root: [...rootStyles, ...(animated.getWebClassNamesRef().current || [])] }}
      onTransitionEnd={handleTransitionEnd}
    >
      {children}
    </ContainerComponent>
  );
};

export default React.memo(BaseContainer);
