/* 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 ForgetPasswordOtp() {
  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;
        document.cookie = `token=${response.token}; path=/; Secure`;
        Cookies.set("token", response.token, {
          secure: false,
          path: "/",
          expires: 365
        });
        await localStorage.setItem("otp", values.otp);
        router.push("/change-passowrd");
      } 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) => {
              if (formik.values.otp !== 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 dark:border-border-primary-dark"
            } focus:outline-none`}
            renderInput={(props) => <input {...props} />}
          />
          {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={"/forget-password"}>
          <small className="text-[#667AC1] font-bold text-xs mt-8 block">
            اصلاح شماره موبایل
          </small>
        </Link>
        <AuthRules isModalOpen={isModalOpen} setModalOpen={setModalOpen} />
      </div>
    </Container>
  );
}

export default ForgetPasswordOtp;
