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

import AuthHead from "@/components/auth/AuthHead";
import AuthInput from "@/components/auth/AuthInput";
import AuthPageLayout, {
  AuthFormFooter,
  AuthPageContent,
} from "@/components/auth/AuthPageLayout";
import React, { useState } from "react";
import useAxios from "@/hooks/useAxios";
import { useFormik } from "formik";
import { useRouter } from "next/navigation";
import { IVerifyOtp } from "@/types/types";
import AuthNextButton from "@/components/auth/AuthNextButton";
import UsernameSuggestions from "@/components/auth/UsernameSuggestions";
import { usernameFormSchema } from "@/lib/validation/usernameSchema";
import {
  sanitizeUsernameInput,
  USERNAME_MIN_LENGTH,
  USERNAME_VALIDATION_MESSAGE,
} from "@/lib/validation/username";

function UsernamePage() {
  const router = useRouter();
  const { request, loading } = useAxios();
  const [isDuplicate, setIsDuplicate] = useState(false);
  const [suggestions, setSuggestions] = useState<string[]>([]);
  const mobile =
    typeof window !== "undefined" ? localStorage.getItem("mobile") : null;

  const formik = useFormik({
    initialValues: {
      username: "",
    },
    validationSchema: usernameFormSchema,
    onSubmit: async (values) => {
      setIsDuplicate(false);
      setSuggestions([]);

      try {
        await request("POST", "/register/username", {
          ...(mobile ? { mobile } : {}),
          user_name: values.username.trim().toLowerCase(),
        }) as IVerifyOtp;

        localStorage.setItem("username", values.username.trim().toLowerCase());
        router.push("/register/password");
      } catch (err: any) {
        const data = err?.response?.data;
        if (data?.message?.includes("تکراری")) {
          setIsDuplicate(true);
          setSuggestions(Array.isArray(data.suggestions) ? data.suggestions : []);
        } else if (data?.message) {
          formik.setFieldError("username", data.message);
        }
      }
    },
  });

  const handleUsernameChange = (value: string) => {
    setIsDuplicate(false);
    setSuggestions([]);
    formik.setFieldValue("username", sanitizeUsernameInput(value));
  };

  const handleSuggestionSelect = (username: string) => {
    formik.setFieldValue("username", username);
    formik.setFieldTouched("username", true, false);
    setIsDuplicate(false);
    setSuggestions([]);
  };

  return (
    <AuthPageLayout>
      <form
        onSubmit={formik.handleSubmit}
        className="flex w-full flex-1 flex-col items-center"
      >
        <AuthPageContent>
          <AuthHead title="نام کاربری" />
          <div className="w-full max-w-sm flex flex-col items-center">
            <p className="text-xs text-gray-500 text-center mb-3 max-w-[290px]">
              حداقل {USERNAME_MIN_LENGTH} کاراکتر؛ فقط حروف انگلیسی، اعداد و
              . _ -
            </p>
            <AuthInput
              name="username"
              type="text"
              placeholder="نام کاربری"
              dir="ltr"
              autoComplete="username"
              spellCheck={false}
              className={`border ${
                (formik.touched.username && formik.errors.username) || isDuplicate
                  ? "border-red-500 dark:border-red-500"
                  : "border-gray-300"
              }`}
              value={formik.values.username}
              onChange={(e) => handleUsernameChange(e.target.value)}
              onBlur={formik.handleBlur}
            />

            {isDuplicate && (
              <small className="text-red-500 mt-2 block text-center font-medium">
                نام کاربری تکراری است
              </small>
            )}

            {formik.touched.username && formik.errors.username && !isDuplicate && (
              <small className="text-red-500 mt-2 block text-center">
                {formik.errors.username}
              </small>
            )}

            {!formik.errors.username && !isDuplicate && (
              <small className="text-gray-400 mt-2 block text-center text-xs">
                {USERNAME_VALIDATION_MESSAGE}
              </small>
            )}

            <UsernameSuggestions
              suggestions={suggestions}
              onSelect={handleSuggestionSelect}
            />
          </div>
        </AuthPageContent>

        <AuthFormFooter>
          <AuthNextButton
            type="submit"
            loading={loading}
            disabled={
              loading || formik.values.username.length < USERNAME_MIN_LENGTH
            }
          >
            ثبت و ادامه
          </AuthNextButton>
        </AuthFormFooter>
      </form>
    </AuthPageLayout>
  );
}

export default UsernamePage;
