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

import AuthButton from "@/components/auth/AuthButton";
import AuthHead from "@/components/auth/AuthHead";
import Container from "@/components/elements/Container";
import AuthRules from "@/components/auth/AuthRules";
import Link from "next/link";
import React, { useMemo, useState } from "react";
import AuthOtpInput from "@/components/auth/AuthOtpInput";
import AuthOtpStatus from "@/components/auth/AuthOtpStatus";
import useAxios from "@/hooks/useAxios";
import { useFormik } from "formik";
import * as yup from "yup";
import { useRouter } from "next/navigation";
import { IVerifyOtp } from "@/types/types";
import { setAuthSession } from "@/lib/auth/session";
import { AUTH_SUCCESS_DELAY_MS, pause } from "@/lib/auth/feedback";
import { useTranslation } from "react-i18next";
import LocalePageShell from "@/components/i18n/LocalePageShell";

function ForgetPasswordOtp() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const [isModalOpen, setModalOpen] = useState(false);
  const [otpExpired, setOtpExpired] = useState(false);
  const [resendLoading, setResendLoading] = useState(false);
  const [isSuccess, setIsSuccess] = useState(false);
  const [otpError, setOtpError] = useState(false);
  const { request, loading } = useAxios();
  const mobile =
    typeof window !== "undefined" ? localStorage.getItem("mobile") : null;

  const schema = useMemo(
    () =>
      yup.object({
        otp: yup
          .string()
          .matches(/^\d{6}$/, t("auth.otpInvalid"))
          .required(t("auth.otpRequired")),
      }),
    [t]
  );

  const formik = useFormik({
    initialValues: {
      otp: "",
      mobile: "",
    },
    validationSchema: schema,
    onSubmit: async (values: { mobile: string; otp: string }) => {
      const mobile = localStorage.getItem("mobile");
      if (!mobile) {
        console.log("Mobile number is missing in localStorage!");
        return;
      }

      try {
        const response = (await request("POST", "/login/verify", {
          mobile,
          otp: values.otp.trim(),
        })) as IVerifyOtp;
        await setAuthSession(response.token);
        await localStorage.setItem("otp", values.otp);
        setIsSuccess(true);
        await pause(AUTH_SUCCESS_DELAY_MS);
        router.push("/change-passowrd");
      } catch (err: any) {
        setOtpError(true);
        setIsSuccess(false);
        console.log("Unhandled error:", err?.message);
      }
    },
  });

  return (
    <LocalePageShell>
      <Container>
        <div className="p-4 flex flex-col items-center h-screen justify-center">
          <AuthHead title={t("auth.forgetPasswordTitle")} />
          <AuthOtpStatus
            mobile={mobile}
            resendLoading={resendLoading}
            onExpiredChange={setOtpExpired}
            onResend={async () => {
              if (!mobile) return;
              setResendLoading(true);
              try {
                await request("POST", "/login", { mobile });
                formik.setFieldValue("otp", "");
                setOtpError(false);
                setIsSuccess(false);
              } finally {
                setResendLoading(false);
              }
            }}
          />
          <form
            onSubmit={formik.handleSubmit}
            className="w-full max-w-sm flex flex-col items-center"
          >
            <AuthOtpInput
              className="mt-3"
              value={formik.values.otp}
              onChange={(otp) => {
                formik.setFieldValue("otp", otp);
                setOtpError(false);
                setIsSuccess(false);
              }}
              onComplete={() => setTimeout(() => formik.submitForm(), 400)}
              error={otpError || Boolean(formik.touched.otp && formik.errors.otp)}
              success={isSuccess}
              disabled={loading || otpExpired || isSuccess}
            />
            {formik.touched.otp && formik.errors.otp && (
              <small className="text-red-500 mt-2">{formik.errors.otp}</small>
            )}
            <AuthButton
              type="submit"
              className="mt-5"
              loading={loading}
              disabled={
                loading ||
                otpExpired ||
                isSuccess ||
                formik.values.otp.length !== 6
              }
            >
              {t("auth.verifyCode")}
            </AuthButton>
          </form>
          <Link href={"/login-with-username"}>
            <small className="text-[#FF5C00] font-bold text-xs mt-8 block">
              {t("auth.loginWithUsername")}
            </small>
          </Link>
          <Link href={"/forget-password"}>
            <small className="text-[#667AC1] font-bold text-xs mt-8 block">
              {t("auth.editMobile")}
            </small>
          </Link>
          <AuthRules isModalOpen={isModalOpen} setModalOpen={setModalOpen} />
        </div>
      </Container>
    </LocalePageShell>
  );
}

export default ForgetPasswordOtp;
