import { motion } from 'framer-motion';
import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { TITLESIZE, SUBTITLESIZE, TEXTPOSITION } from '../../models/common';
import { ThemeOverflow } from '../../redux/reducers/themeReducer/model';
import { RootState } from '../../redux/store';
import styles from './TeamIntro.module.scss';

type Props = {
  title?: string;
  subTitle?: string;
  titleSize?: TITLESIZE;
  subTitleSize?: SUBTITLESIZE;
  containerPosition?: TEXTPOSITION;
};

interface State {
  overflow: ThemeOverflow;
  mounted: boolean;
}

const teamIntroVariants = {
  inactive: {
    opacity: 0,
    height: 0,
  },
  active: {
    opacity: 1,
    height: 'auto',
  },
};

const TeamIntro = (props: Props): JSX.Element => {
  const { overflow } = useSelector((state: RootState) => state.theme);
  const [state, setState] = useState<State>({
    overflow: ThemeOverflow.HIDDEN,
    mounted: false,
  });
  const { title, subTitle, titleSize, subTitleSize, containerPosition } = props;

  useEffect(() => {
    if (state.mounted) setState({ ...state, overflow: ThemeOverflow.VISIBLE });
  }, [overflow]);

  useEffect(() => {
    if (overflow !== ThemeOverflow.VISIBLE)
      setState({ ...state, mounted: true });
  }, [overflow]);
  return (
    <motion.div
      initial={false}
      animate={state.overflow === ThemeOverflow.HIDDEN ? 'inactive' : 'active'}
      variants={teamIntroVariants}
      className={`${styles.teamIntro} ${
        containerPosition
          ? styles[containerPosition]
          : styles[TEXTPOSITION.DEFAULT]
      }`}
    >
      {title && (
        <div className={`${styles.title} ${titleSize || TITLESIZE.DEFAULT}`}>
          {title}
        </div>
      )}
      {subTitle && (
        <div
          className={`${subTitleSize || SUBTITLESIZE.DEFAULT} ${
            styles.subTitle
          }`}
        >
          {subTitle}
        </div>
      )}
    </motion.div>
  );
};
export default TeamIntro;
