/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";
import React, { useState } from "react";
import { useFormik } from "formik";
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";
import UsernameSuggestions from "@/components/auth/UsernameSuggestions";
import { usernameFormSchema } from "@/lib/validation/usernameSchema";
import { sanitizeUsernameInput, USERNAME_MIN_LENGTH } from "@/lib/validation/username";

function UsernamePage() {
  const router = useRouter();
  const user = useUser();
  const { request, loading } = useAxios();
  const [isDuplicate, setIsDuplicate] = useState(false);
  const [suggestions, setSuggestions] = useState<string[]>([]);

  const formik = useFormik({
    initialValues: {
      username: user?.user_name || "",
    },
    validationSchema: usernameFormSchema,
    enableReinitialize: true,
    onSubmit: async (values) => {
      setIsDuplicate(false);
      setSuggestions([]);

      try {
        await request("PATCH", "/register/username", {
          user_name: values.username.trim().toLowerCase(),
        });
        localStorage.setItem("username", values.username.trim().toLowerCase());
        router.push("/settings/edit");
      } 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 (
    <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="نام کاربری"
            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>
          )}

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

          <AuthNextButton
            type="submit"
            className="mt-20"
            loading={loading} disabled={loading || formik.values.username.length < USERNAME_MIN_LENGTH}
          >
            ویرایش
          </AuthNextButton>
        </form>
      </div>
    </Container>
  );
}

export default UsernamePage;
