/* 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, { 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 { getRegistrationRoute } from "@/lib/auth/registrationRoutes";

// Validation schema using Yup
const schema = yup.object({
  otp: yup
    .string()
    .matches(/^\d{6}$/, "کد وارد شده صحیح نیست")
    .required("کد تایید را وارد کنید"),
});

function VerifyOtp() {
  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 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;

        switch (response?.page) {
          case "home":
            await setAuthSession(response.token, {
              id: response.id,
              user_type: response.user_type,
              step: response.step,
              auth_provider: response.auth_provider,
              email: response.email ?? undefined,
            });
            setIsSuccess(true);
            await pause(AUTH_SUCCESS_DELAY_MS);
            router.refresh();
            router.push("/");
            break;
          case "auth-page":
            await setAuthSession(response.token, {
              id: response.id,
              step: response.step,
            });
            setIsSuccess(true);
            await pause(AUTH_SUCCESS_DELAY_MS);
            router.push(getRegistrationRoute(response.step));
            break;
          default:
            break;
        }
        // router.push("/dashboard");
      } catch (err: any) {
        setOtpError(true);
        setIsSuccess(false);
        console.log("Unhandled error:", err?.message);
      }
    },
  });

  return (
    <Container>
      <div className="p-4 flex flex-col items-center h-screen justify-center">
        <AuthHead title="ورود" />
        <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}
          >
            تایید کد
          </AuthButton>
        </form>
        <Link href={"/login-with-username"}>
          <small className="text-[#FF5C00] font-bold text-xs mt-8 block">
            با نام کاربری و کلمه عبور خود وارد شوید
          </small>
        </Link>
        <Link href={"/login"}>
          <small className="text-[#667AC1] font-bold text-xs mt-8 block">
            اصلاح شماره موبایل
          </small>
        </Link>
        <AuthRules isModalOpen={isModalOpen} setModalOpen={setModalOpen} />
      </div>
    </Container>
  );
}

export default VerifyOtp;
