import { ApiError, extractErrorMessage, useApi } from "@/api";
import Loader from "../Loader";
import styles from "./styles.module.css";
import { useEffect, useState } from "react";
import Title from "../Title";
import MainButton from "../MainButton";
import { useNavigate } from "react-router-dom";
import { navigateToAuth } from "@/utils/auth-navigation";
import routes from "@/routes";
import { useAuth } from "@/auth";
import ErrorText from "../ErrorText";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";

function AuthResultPage(): JSX.Element {
  const api = useApi();
  const { signUp } = useAuth();
  const dispatch = useDispatch();
  const birthday = useSelector(selectors.selectBirthday);
  const [apiError, setApiError] = useState<ApiError | null>(null);
  const [error, setError] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const navigate = useNavigate();
  const queryParameters = new URLSearchParams(window.location.search);
  const access_token = queryParameters.get("jwt") || "";

  useEffect(() => {
    (async () => {
      try {
        setIsLoading(true);
        const apiUser = await api.getUser({ token: access_token });
        signUp(access_token, apiUser.user);
        const payload = {
          user: { profile_attributes: { birthday } },
          token: access_token,
        };
        const updatedUser = await api.updateUser(payload).catch((error) => {
          console.log("Error: ", error);
        });
        if (updatedUser?.user) {
          dispatch(actions.user.update(updatedUser.user));
        }
        dispatch(actions.status.update("registred"));
        setIsLoading(false);
        setTimeout(() => {
          navigate(routes.client.priceList());
        }, 1500);
      } catch (error) {
        console.error(error);
        if (error instanceof ApiError) {
          setApiError(error as ApiError);
        } else {
          setError(true);
        }
        setIsLoading(false);
      }
    })();
  }, [access_token, api, birthday, dispatch, navigate, signUp]);

  const handleTryAgain = () => {
    // Use server-side navigation to ensure redirects work properly
    navigateToAuth(undefined, true);
  };

  return (
    <section className={`${styles.page} page`}>
      {isLoading && <Loader />}
      {(error || apiError) && (
        <>
          <Title>Something went wrong</Title>
          <MainButton onClick={handleTryAgain}>Try again</MainButton>
        </>
      )}
      {apiError && (
        <ErrorText
          size="medium"
          isShown={Boolean(apiError)}
          message={apiError ? extractErrorMessage(apiError) : null}
        />
      )}
      {!apiError && !error && !isLoading && access_token.length && (
        <img src="/SuccessIcon.webp" alt="Success Icon" />
      )}
    </section>
  );
}

export default AuthResultPage;
