/* eslint-disable @next/next/no-img-element */
import { motion, useAnimation } from 'framer-motion';
import { useEffect, useState } from 'react';
import styles from './styles.module.scss';

interface Props {
  type: 'error' | 'success';
  message: string;
  hideComplete?: () => void;
}

const variants = {
  initial: {
    height: '0px',
  },
  hide: {
    height: '0px',
  },
  show: {
    height: 'auto',
  },
};

const FormMessage = (props: Props) => {
  const { type, hideComplete } = props;
  const controls = useAnimation();
  const [message, setMessage] = useState<string | null>();

  useEffect(() => {
    if (!message) return;
    const startAnimation = async () => {
      controls.set('initial');
      await controls.start('show');
      await new Promise((resolve) => setTimeout(resolve, 4000));
      await controls.start('hide');
      if (hideComplete) hideComplete();
    };
    startAnimation();
  }, [message]);

  useEffect(() => {
    setMessage(props.message);
  }, [props]);

  return (
    <motion.div
      className={`${styles.formMessage} ${styles[type]}`}
      initial={'initial'}
      animate={controls}
      variants={variants}
    >
      <div className={styles.container}>
        <motion.img
          src={
            type === 'error'
              ? '/imgs/icons/error.svg'
              : '/imgs/icons/success.svg'
          }
          alt=""
        />
        <motion.div>{message}</motion.div>
      </div>
    </motion.div>
  );
};

export default FormMessage;
