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 { createSession } from "store/reducers/ActionCreator";
import { sessionSlice } from "store/reducers/sessionSlice";

export const PopupComponent: React.FC = () => {
  const dispatch = useAppDispatch();
  const { currentCard } = useAppSelector((state) => state.cardReducer);
  const [visible, setVisible] = useState({
    connectPopup: true,
    loadingPopup: false,
  });

  const { cleanErrors } = sessionSlice.actions;

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

  const { connectPopup, loadingPopup } = visible;

  useEffect(() => {
    if (isLoading) {
      setVisible({ connectPopup: false, loadingPopup: true });
      return;
    } else if (error) {
      setVisible({ connectPopup: false, loadingPopup: false });
      return;
    }
  }, [isLoading, error]);

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

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