"use client";

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

// Validation schema using Yup
const schema = yup.object({
  mobile: yup
    .string()
    .matches(/^(09\d{9})$/, "شماره موبایل معتبر نیست")
    .required("شماره موبایل الزامی است"),
});

function ForgetPassword() {
  const router = useRouter();
  const { request, loading } = useAxios();

  const formik = useFormik({
    initialValues: {
      mobile: "",
    },
    validationSchema: schema,
    onSubmit: async (values) => {
      try {
        await request("POST", "/login", { mobile: values.mobile });
        await localStorage.setItem("mobile", values.mobile);
        router.push("/forget-password-otp");
      } catch (err) {
        console.log(err);
      }
    },
  });

  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"
        >
          <AuthInput
            name="mobile"
            maxLength={11}
            type="text"
            placeholder="09 _ _ _ _ _ _ _ _ _"
            className={`border ${
              formik.touched.mobile && formik.errors.mobile
                ? "border-red-500 dark:border-red-500"
                : "border-gray-300"
            }`}
            value={formik.values.mobile}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
          />
          {formik.touched.mobile && formik.errors.mobile && (
            <small className="text-red-500 mt-2 block">
              {formik.errors.mobile}
            </small>
          )}
          <AuthButton type="submit" className="mt-5" disabled={loading}>
            {loading ? "در حال ارسال..." : "ارسال کد"}
          </AuthButton>
        </form>
        <Link href={"/register"}>
          <small className="text-[#292D32] font-bold text-xs mt-8 block">
            حساب کاربری ندارید؟ <span className="text-[#0033EA]">ثبت نام</span>
          </small>
        </Link>
      </div>
    </Container>
  );
}

export default ForgetPassword;
