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

function Login() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const [isModalOpen, setModalOpen] = useState(false);
  const { request, loading } = useAxios();
  useAuthSessionRedirect();
  const redirectPath = getSafeRedirectPath();
  const usernameLoginHref =
    redirectPath !== "/"
      ? `/login-with-username?redirect=${encodeURIComponent(redirectPath)}`
      : "/login-with-username";

  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) => {
      try {
        await request("POST", "/login", { mobile: values.mobile });
        await localStorage.setItem("mobile", values.mobile);
        markOtpSent();
        router.push("/verify-otp");
      } catch (err) {
        console.log(err);
      }
    },
  });

  return (
    <LocalePageShell>
      <Container>
        <div className="p-4 flex flex-col items-center h-screen justify-center">
          <AuthHead title={t("auth.login")} />
          <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}>
              {t("auth.sendCode")}
            </AuthButton>
          </form>
          <GoogleSignInButton mode="login" />
          <InstagramSignInButton mode="login" />
          <Link href={usernameLoginHref}>
            <small className="text-[#FF5C00] font-bold text-xs mt-8 block">
              {t("auth.loginWithUsername")}
            </small>
          </Link>
          <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 Login;
