"use client";

import AuthHead from "@/components/auth/AuthHead";
import AuthOtpInput from "@/components/auth/AuthOtpInput";
import AuthButton from "@/components/auth/AuthButton";
import Container from "@/components/elements/Container";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import useAxios from "@/hooks/useAxios";
import { completeLogin, getSafeRedirectPath } from "@/lib/auth/postLogin";
import { IVerifyOtp } from "@/types/types";
import { useRouter } from "next/navigation";
import React, { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

export default function LoginTwoFactorPage() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const { request, loading } = useAxios();
  const [code, setCode] = useState("");
  const [tempToken, setTempToken] = useState("");

  useEffect(() => {
    const token =
      typeof window !== "undefined"
        ? sessionStorage.getItem("login_2fa_temp")
        : null;
    if (!token) {
      router.replace("/login");
      return;
    }
    setTempToken(token);
  }, [router]);

  const handleVerify = async () => {
    if (!tempToken || code.length !== 6) return;

    try {
      const response = (await request("POST", "/auth/totp/verify-login", {
        temp_token: tempToken,
        code,
      })) as IVerifyOtp;

      sessionStorage.removeItem("login_2fa_temp");

      const loggedIn = await completeLogin(router, response, {
        redirectTo: getSafeRedirectPath(),
      });

      if (!loggedIn) {
        toast.error(t("auth.invalidServerResponse"));
      }
    } catch {
      toast.error(t("settings.edit.twoFactor.invalidCode"));
    }
  };

  return (
    <LocalePageShell>
      <Container>
        <div className="flex h-screen flex-col items-center justify-center p-4">
          <AuthHead title={t("auth.twoFactorTitle")} />
          <p className="mb-6 max-w-sm text-center text-sm text-neutral-500">
            {t("auth.twoFactorHint")}
          </p>
          <AuthOtpInput
            value={code}
            onChange={setCode}
            onComplete={() => setTimeout(handleVerify, 300)}
            disabled={loading || !tempToken}
          />
          <AuthButton
            type="button"
            className="mt-5"
            loading={loading}
            disabled={loading || code.length !== 6 || !tempToken}
            onClick={handleVerify}
          >
            {t("auth.verifyCode")}
          </AuthButton>
        </div>
      </Container>
    </LocalePageShell>
  );
}
