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

import AuthButton from "@/components/auth/AuthButton";
import AuthHead from "@/components/auth/AuthHead";
import AuthInput from "@/components/auth/AuthInput";
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";
import { setAuthSession } from "@/lib/auth/session";
import { AUTH_SUCCESS_DELAY_MS, pause } from "@/lib/auth/feedback";

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

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

  const formik = useFormik({
    initialValues: {
      username: "",
      password: "",
    },
    validationSchema: schema,
    onSubmit: async (values) => {
      try {
        const response = (await request("POST", "/login/login_username", {
          mobile,
          user_name: values.username,
          password: values.password,
        })) as IVerifyOtp;
        switch (response?.page) {
          case "home":
            await setAuthSession(response.token, {
              id: response.id,
              user_type: response.user_type,
              step: response.step,
            });
            setIsSuccess(true);
            await pause(AUTH_SUCCESS_DELAY_MS);
            router.refresh();
            router.push("/");
            break;
          case "auth-page":
            await setAuthSession(response.token, {
              id: response.id,
              step: response.step,
            });
            setIsSuccess(true);
            await pause(AUTH_SUCCESS_DELAY_MS);
            router.push("/auth");
            break;
          default:
            break;
        }
      } catch (err: any) {
        setAuthError(true);
        setIsSuccess(false);
        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"
        >
          <AuthInput
            name="username"
            type="text"
            placeholder="نام کاربری"
            success={isSuccess}
            error={authError || Boolean(formik.touched.username && formik.errors.username)}
            value={formik.values.username}
            onChange={(e) => {
              setAuthError(false);
              setIsSuccess(false);
              formik.handleChange(e);
            }}
            onBlur={formik.handleBlur}
            disabled={loading || isSuccess}
          />
          {formik.touched.username && formik.errors.username && !authError && (
            <small className="text-red-500 mt-2 block">
              {formik.errors.username}
            </small>
          )}
          <AuthPasswordInput
            name="password"
            placeholder="کلمه عبور"
            wrapperClassName="mt-4"
            success={isSuccess}
            error={authError || Boolean(formik.touched.password && formik.errors.password)}
            value={formik.values.password}
            onChange={(e) => {
              setAuthError(false);
              setIsSuccess(false);
              formik.handleChange(e);
            }}
            onBlur={formik.handleBlur}
            disabled={loading || isSuccess}
          />
          {formik.touched.password && formik.errors.password && !authError && (
            <small className="text-red-500 mt-2 block">
              {formik.errors.password}
            </small>
          )}
          <AuthButton type="submit" className="mt-5" loading={loading} disabled={loading || isSuccess}>
            ورود
          </AuthButton>
        </form>
        <Link href={"/forget-password"}>
          <small className="text-[#FF5C00] font-bold text-xs mt-8 block">
            کلمه عبور خود را فراموش کرده اید؟
          </small>
        </Link>
        <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 LoginWithUsername;
