/* 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, { useEffect, 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 {
  completeLogin,
  getAxiosErrorMessage,
  getSafeRedirectPath,
} from "@/lib/auth/postLogin";
import { clearAuthSession } from "@/lib/auth/session";
import toast from "react-hot-toast";

const schema = yup.object().shape({
  username: yup.string().required("نام کاربری الزامی است"),
  password: yup
    .string()
    .required("کلمه عبور نمی\u200Cتواند خالی باشد")
    .min(8, "کلمه عبور نباید کوتاه تر از 8 کاراکتر باشد"),
});

function LoginWithUsername() {
  const router = useRouter();
  const [isModalOpen, setModalOpen] = useState(false);
  const [isSuccess, setIsSuccess] = useState(false);
  const [authError, setAuthError] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");
  const { request, loading } = useAxios();
  const redirectPath = getSafeRedirectPath();

  useEffect(() => {
    void clearAuthSession();
  }, []);

  const formik = useFormik({
    initialValues: {
      username: "",
      password: "",
    },
    validationSchema: schema,
    onSubmit: async (values) => {
      setAuthError(false);
      setErrorMessage("");

      try {
        const response = (await request(
          "POST",
          "/login/login_username",
          {
            user_name: values.username.trim(),
            password: values.password,
          },
          { noToast: true }
        )) as IVerifyOtp;

        const loggedIn = await completeLogin(router, response, {
          redirectTo: redirectPath,
        });

        if (!loggedIn) {
          const message = "پاسخ سرور نامعتبر بود. دوباره تلاش کنید.";
          setAuthError(true);
          setErrorMessage(message);
          toast.error(message);
          return;
        }

        setIsSuccess(true);
      } catch (err: any) {
        const message = getAxiosErrorMessage(err);
        setAuthError(true);
        setIsSuccess(false);
        setErrorMessage(message);
        toast.error(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);
              setErrorMessage("");
              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);
              setErrorMessage("");
              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>
          )}
          {authError && errorMessage && (
            <small className="text-red-500 mt-2 block text-center">
              {errorMessage}
            </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;
