"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, { useMemo, 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, InstagramSignInButton } from "@/app/(auth)/AuthProviders";
import { MOBILE_NUMERIC_INPUT_PROPS } from "@/lib/auth/inputProps";
import { getAxiosErrorMessage } from "@/lib/auth/postLogin";
import { useTranslation } from "react-i18next";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import toast from "react-hot-toast";
import Link from "next/link";

function normalizeMobileInput(value: string): string {
  return value.replace(/\D/g, "").slice(0, 11);
}

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

  const schema = useMemo(
    () =>
      yup.object({
        mobile: yup
          .string()
          .matches(/^(09\d{9})$/, t("auth.mobileInvalid"))
          .required(t("auth.mobileRequired")),
      }),
    [t]
  );

  const formik = useFormik({
    initialValues: {
      mobile: "",
    },
    validationSchema: schema,
    onSubmit: async (values) => {
      const mobile = normalizeMobileInput(values.mobile);

      try {
        await request(
          "POST",
          "/register",
          { mobile },
          { noToast: true }
        );
        localStorage.setItem("mobile", mobile);
        markOtpSent();
        router.push("/register-otp");
      } catch (err: unknown) {
        const data = (
          err as {
            response?: {
              data?: { message?: string; code?: string; errors?: Array<{ msg?: string }> };
            };
          }
        )?.response?.data;

        const message =
          data?.message ||
          data?.errors?.[0]?.msg ||
          getAxiosErrorMessage(err, i18n.language === "en" ? "en" : "fa");

        toast.error(message);

        if (data?.code === "ALREADY_REGISTERED") {
          setTimeout(() => {
            router.push("/login");
          }, 1200);
        }
      }
    },
  });

  return (
    <LocalePageShell>
      <Container>
        <div className="p-4 flex flex-col items-center h-screen justify-center">
          <AuthHead title={t("auth.register")} />
          <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={(e) =>
                formik.setFieldValue(
                  "mobile",
                  normalizeMobileInput(e.target.value)
                )
              }
              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 || formik.values.mobile.length !== 11}
            >
              {t("auth.sendCode")}
            </AuthButton>
          </form>
          <GoogleSignInButton mode="register" />
          <InstagramSignInButton mode="register" />
          <Link href="/login">
            <small className="text-[#292D32] dark:text-neutral-300 font-bold text-xs mt-6 block text-center">
              {t("auth.haveAccount")}{" "}
              <span className="text-[#0033EA]">{t("auth.login")}</span>
            </small>
          </Link>
          <button type="button" onClick={() => setModalOpen(true)} className="mb-2">
            <small className="text-[#FF5C00] font-bold text-xs mt-8 block">
              {t("auth.rules")}
            </small>
          </button>
          <AuthRules isModalOpen={isModalOpen} setModalOpen={setModalOpen} />
        </div>
      </Container>
    </LocalePageShell>
  );
}

export default Register;
