/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";
import React, { useEffect } from "react";
import { useFormik } from "formik";
import * as yup from "yup";
import { useRouter } from "next/navigation";
import useAxios from "@/hooks/useAxios";
import { useUser } from "@/hooks/useUser";
import AuthHead from "@/components/auth/AuthHead";
import AuthInput from "@/components/auth/AuthInput";
import AuthNextButton from "@/components/auth/AuthNextButton";
import Container from "@/components/elements/Container";

// Validation schema using Yup
const schema = yup.object().shape({
  username: yup.string().required("نام کاربری الزامی است"),
});

function UsernamePage() {
  const router = useRouter();
  const user = useUser();
  const { request, loading } = useAxios();

  const formik = useFormik({
    initialValues: {
      username: user?.user_name || "",
    },
    validationSchema: schema,
    onSubmit: async (values) => {
      try {
        await request("PATCH", "/register/username", {
          user_name: values.username,
        });
        localStorage.setItem("username", values.username);
        router.push("/settings/edit");
      } catch (err: any) {
        console.log("Unhandled error:", err?.message);
      }
    },
  });

  // آپدیت مقدار username در صورتی که user.user_name مقدار داشته باشد
  useEffect(() => {
    if (user?.user_name) {
      formik.setValues({ username: user.user_name });
    }
  }, [user?.user_name]);

  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="نام کاربری خود را وارد کنید"
            className={`border ${
              formik.touched.username && formik.errors.username
                ? "border-red-500 dark:border-red-500"
                : "border-gray-300"
            }`}
            value={formik.values.username}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
          />
          {formik.touched.username && formik.errors.username && (
            <small className="text-red-500 mt-2 block">
              {formik.errors.username}
            </small>
          )}
          <AuthNextButton type="submit" className="mt-20" disabled={loading}>
            {loading ? "در حال ارسال..." : "ویرایش"}
          </AuthNextButton>
        </form>
      </div>
    </Container>
  );
}

export default UsernamePage;
