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 { userVerifyAsync, VerifyStateSelector } from "features/verify";

const UserVerifyPage: 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(() => {
    if (!jwt) {
      navigate("/mail-confirm/failed");
    }
    dispatch(userVerifyAsync({ jwt }));
  }, [navigate, 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 UserVerifyPage;
