"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 AuthRules from "@/components/auth/AuthRules";
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 { markOtpSent } from "@/lib/auth/otpTimer";
import GoogleSignInButton from "@/components/auth/GoogleSignInButton";
import { MOBILE_NUMERIC_INPUT_PROPS } from "@/lib/auth/inputProps";

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

function Register() {
  const router = useRouter();
  const [isModalOpen, setModalOpen] = useState(false);
  const { request, loading } = useAxios();

  const formik = useFormik({
    initialValues: {
      mobile: "",
    },
    validationSchema: schema,
    onSubmit: async (values) => {
      try {
        await request("POST", "/register", { mobile: values.mobile });
        await localStorage.setItem("mobile", values.mobile);
        markOtpSent();
        router.push("/register-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}
            {...MOBILE_NUMERIC_INPUT_PROPS}
            dir="ltr"
            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" loading={loading} disabled={loading}>
            ارسال کد
          </AuthButton>
        </form>
        <GoogleSignInButton mode="register" />
        <button onClick={() => setModalOpen(true)} className="mb-2">
          <small className="text-[#FF5C00] font-bold text-xs mt-8 block">
            قوانین و مقررات
          </small>
        </button>
        <AuthRules isModalOpen={isModalOpen} setModalOpen={setModalOpen} />
      </div>
    </Container>
  );
}

export default Register;
