/* 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 OtpInput from "react-otp-input";
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 Cookies from "js-cookie";

// 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 { 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":
            Cookies.set("token", response.token, {
              secure: false,
              path: "/",
              expires: 365,
            });
            await localStorage.setItem("usertype", response.user_type);
            await localStorage.setItem("id", response.id);
            await localStorage.setItem("step", response.step);
            router.push("/");
            break;
          case "auth-page":
            Cookies.set("token", response.token, {
              secure: false,
              path: "/",
              expires: 365,
            });
            // await localStorage.setItem("usertype", response.user_type);
            await localStorage.setItem("id", response.id);
            await localStorage.setItem("step", response.step);

            switch (response.step) {
              case "user_name":
                router.push("/register/username");
                break;
              case "password":
                router.push("/register/password");
                break;
              case "first_name":
                router.push("/register/fullname");
                break;
              case "user_type":
                router.push("/register/usertype");
                break;
              default:
                router.push("/verify/avatar");
                break;
            }
            break;
          default:
            break;
        }
        // router.push("/dashboard");
      } catch (err: any) {
        console.log("Unhandled error:", err?.message);
      }
    },
  });

  return (
    <Container>
      <div className="p-4 flex flex-col items-center h-screen justify-center">
        <AuthHead title="ورود" />
        <small className="mb-10">کد 6 رقمی به شماره {mobile} ارسال شد</small>
        <form
          onSubmit={formik.handleSubmit}
          className="w-full max-w-sm flex flex-col items-center"
        >
          <OtpInput
            value={formik.values.otp}
            onChange={(otp) => {
              formik.setFieldValue("otp", otp);
              if (otp.length === 6) {
                setTimeout(() => formik.submitForm(), 500);
              }
            }}
            numInputs={6}
            containerStyle="mt-3 dir-ltr flex gap-x-4 justify-center"
            inputStyle={`text-center min-w-[30px] border bg-secondary-light dark:bg-secondary-dark rounded-2xl py-3 ${
              formik.touched.otp && formik.errors.otp
                ? "border-red-500 dark:border-red-500"
                : "border-border-primary-light "
            } focus:outline-none`}
            renderInput={(props) => (
              <input
                {...props}
                type="tel"
                inputMode="numeric"
                pattern="[0-9]*"
              />
            )}
          />

          {formik.touched.otp && formik.errors.otp && (
            <small className="text-red-500 mt-2">{formik.errors.otp}</small>
          )}
          <AuthButton
            type="submit"
            className="mt-5"
            disabled={loading || formik.values.otp.length !== 6}
          >
            {loading ? "در حال ارسال..." : "تایید کد"}
          </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;
