import { useEffect, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";

import { popupAnimation } from "utils/animationProps";

import { PopupConnect } from "components/pages/ConnectPage/PopupConnect/PopupConnect";
import { LoadingPopup } from "components/pages/ConnectPage/LoadingPopup/LoadingPopup";

import { useAppDispatch, useAppSelector } from "hooks/redux";
import { sessionSlice } from "store/reducers/sessionSlice";

export const PopupComponent: React.FC = () => {
  const dispatch = useAppDispatch();
  const { currentCard } = useAppSelector((state) => state.cardReducer);

  const { cleanErrors } = sessionSlice.actions;

  const { isLoading } = useAppSelector((state) => state.sessionReducer);



  useEffect(() => {
    return () => {
      dispatch(cleanErrors());
    };
  }, []);

  return (
    <AnimatePresence mode="wait">
      {!isLoading && (
        <motion.div
          key={1}
          variants={popupAnimation}
          initial={"hidden"}
          animate={"show"}
          exit={"hidden"}
        >
          <PopupConnect
            title={currentCard.app_title}
            isLoading={isLoading}
            logo={currentCard.logo}
          ></PopupConnect>
        </motion.div>
      )}
      {isLoading && (
        <motion.div
          key={2}
          variants={popupAnimation}
          initial={"hidden"}
          animate={"show"}
          exit={"hidden"}
        >
          <LoadingPopup logo={currentCard.logo}></LoadingPopup>
        </motion.div>
      )}
    </AnimatePresence>
  );
};
