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

import AuthButton from "@/components/auth/AuthButton";
import AuthHead from "@/components/auth/AuthHead";
import AuthPasswordInput from "@/components/auth/AuthPasswordInput";
import Container from "@/components/elements/Container";
import AuthRules from "@/components/auth/AuthRules";
import Link from "next/link";
import React, { useState } from "react";
import useAxios from "@/hooks/useAxios";
import { useFormik } from "formik";
import * as yup from "yup";
import { useRouter } from "next/navigation";
import { IVerifyOtp } from "@/types/types";

// Validation schema using Yup
const schema = yup.object().shape({
  password: yup
    .string()
    .required("کلمه عبور نمی\u200Cتواند خالی باشد")
    .min(8, "کلمه عبور نباید کوتاه تر از 8 کاراکتر باشد")
    .matches(
      /^(?=.*[a-zA-Zآ-ی])(?=.*\d).{8,}$/,
      "کلمه عبور باید شامل حروف و اعداد باشد"
    ),
  confirmPassword: yup
    .string()
    .required("تکرار کلمه عبور نمی\u200Cتواند خالی باشد")
    .oneOf(
      [yup.ref("password")],
      "تکرار کلمه عبور باید با کلمه عبور مطابقت داشته باشد"
    )
    .required("تکرار کلمه عبور الزامی است"),
});

function ChangePassword() {
  const router = useRouter();
  const [isModalOpen, setModalOpen] = useState(false);
  const { request, loading } = useAxios();
  const mobile =
    typeof window !== "undefined" ? localStorage.getItem("mobile") : null;
  const otp =
    typeof window !== "undefined" ? localStorage.getItem("otp") : null;

  const formik = useFormik({
    initialValues: {
      password: "",
      confirmPassword: "",
    },
    validationSchema: schema,
    onSubmit: async (values) => {
      try {
        (await request("POST", "/login/change_password", {
          mobile,
          otp,
          new_password: values.password,
        })) as IVerifyOtp;
        router.push("/login");
      } 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="تغییر کلمه عبور" />
        <form
          onSubmit={formik.handleSubmit}
          className="w-full max-w-sm flex flex-col items-center"
        >
          <AuthPasswordInput
            name="password"
            placeholder="کلمه عبور جدید"
            wrapperClassName="mt-4"
            className={`border ${
              formik.touched.password && formik.errors.password
                ? "border-red-500 dark:border-red-500"
                : "border-gray-300"
            }`}
            value={formik.values.password}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
          />
          {formik.touched.password && formik.errors.password && (
            <small className="text-red-500 mt-2 block">
              {formik.errors.password}
            </small>
          )}

          <AuthPasswordInput
            name="confirmPassword"
            placeholder="تکرار کلمه عبور"
            wrapperClassName="mt-4"
            className={`border ${
              formik.touched.confirmPassword && formik.errors.confirmPassword
                ? "border-red-500 dark:border-red-500"
                : "border-gray-300"
            }`}
            value={formik.values.confirmPassword}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
          />
          {formik.touched.confirmPassword && formik.errors.confirmPassword && (
            <small className="text-red-500 mt-2 block">
              {formik.errors.confirmPassword}
            </small>
          )}

          <AuthButton type="submit" className="mt-5" loading={loading} disabled={loading}>
            تغییر کلمه عبور
          </AuthButton>
        </form>

        <Link href={"/register"}>
          <small className="text-[#292D32] font-bold text-xs mt-8 block">
            حساب کاربری ندارید؟ <span className="text-[#0033EA]">ثبت نام</span>
          </small>
        </Link>
        <AuthRules isModalOpen={isModalOpen} setModalOpen={setModalOpen} />
      </div>
    </Container>
  );
}

export default ChangePassword;
