/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import AuthHead from "@/components/auth/AuthHead";
import AuthPageLayout, {
  AuthFormFooter,
  AuthPageContent,
} from "@/components/auth/AuthPageLayout";
import React, { useState } from "react";
import useAxios from "@/hooks/useAxios";
import { useRouter } from "next/navigation";
import AuthNextButton from "@/components/auth/AuthNextButton";
import toast from "react-hot-toast";
import { getSafeRedirectPath } from "@/lib/auth/postLogin";
import { useTranslation } from "react-i18next";
import LocalePageShell from "@/components/i18n/LocalePageShell";

function RegisterCompletePage() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const { request, loading } = useAxios();
  const [action, setAction] = useState<"app" | "continue" | null>(null);

  const finishRegistration = async (next: "app" | "continue") => {
    setAction(next);
    try {
      await request("POST", "/register/user_type", {
        user_type: "user",
      });
      localStorage.setItem("usertype", "user");

      if (next === "continue") {
        router.push("/verify/avatar");
      } else {
        router.push(getSafeRedirectPath());
      }
    } catch (err: any) {
      toast.error(
        err?.response?.data?.message || t("auth.registrationFinishFailed")
      );
    } finally {
      setAction(null);
    }
  };

  return (
    <LocalePageShell>
      <AuthPageLayout>
        <div className="flex w-full flex-1 flex-col items-center">
          <AuthPageContent>
            <AuthHead title={t("auth.registerCompleteTitle")} />
            <p className="text-sm text-gray-500 text-center max-w-sm mt-2">
              {t("auth.registerCompleteDesc")}
            </p>
          </AuthPageContent>

          <AuthFormFooter>
            <div className="flex flex-col sm:flex-row gap-3 w-full max-w-sm justify-center items-center">
              <AuthNextButton
                type="button"
                onClick={() => finishRegistration("continue")}
                className=" w-full sm:w-auto"
                disabled={loading}
                loading={loading && action === "continue"}
              >
                {t("auth.continueRegistration")}
              </AuthNextButton>
              <AuthNextButton
                type="button"
                onClick={() => finishRegistration("app")}
                className="!border-[#FF0000] !text-[#FF0000] w-full sm:w-auto"
                disabled={loading}
                loading={loading && action === "app"}
              >
                {t("auth.enterApp")}
              </AuthNextButton>
            </div>
          </AuthFormFooter>
        </div>
      </AuthPageLayout>
    </LocalePageShell>
  );
}

export default RegisterCompletePage;
