import { AppDispatch } from "app/store";
import Footer from "components/footer";
import Header from "components/header";
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";
import { verifyAsync } from "features/verify";
import { VerifyStateSelector } from "features/verify/selectors";

const VerifyPage: React.FC = (): JSX.Element => {
  const dispatch: AppDispatch = useDispatch();
  const navigate = useNavigate();

  const { search } = useLocation();
  const query = new URLSearchParams(search);
  const jwt = query.get("verify") ?? "";

  useEffect(() => {
    dispatch(verifyAsync({ jwt }));
  }, [dispatch, jwt]);

  const verifystate = useSelector(VerifyStateSelector);

  useEffect(() => {
    switch (verifystate) {
      case "duringVerify":
        // 認証中は処理なし
        break;
      case "success":
        navigate("/mail-confirm/success");
        break;
      case "alreadySuccess":
        navigate("/mail-confirm/alreadyExist");
        break;
      case "failed":
        navigate("/mail-confirm/failed");
        break;
      default:
        // verifystateが列挙型のため到達しない
        break;
    }
  }, [verifystate, navigate]);

  return (
    <>
      <Header />
      <h3>loading ...</h3>
      <Footer />
    </>
  );
};

export default VerifyPage;
