/* 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, { useMemo, 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 AuthNextButton from "@/components/auth/AuthNextButton";
import UsernameSuggestions from "@/components/auth/UsernameSuggestions";
import {
  sanitizeUsernameInput,
  USERNAME_MIN_LENGTH,
  USERNAME_MAX_LENGTH,
  USERNAME_REGEX,
} from "@/lib/validation/username";
import { useTranslation } from "react-i18next";
import LocalePageShell from "@/components/i18n/LocalePageShell";

function UsernamePage() {
  const { t } = useTranslation("common");
  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 instagramSuggestedUsername =
    typeof window !== "undefined" &&
    localStorage.getItem("auth_provider") === "instagram"
      ? sanitizeUsernameInput(localStorage.getItem("instagram_username") || "")
      : "";

  const schema = useMemo(
    () =>
      yup.object({
        username: yup
          .string()
          .required(t("auth.usernameRequired"))
          .min(
            USERNAME_MIN_LENGTH,
            t("auth.usernameMinLength", { min: USERNAME_MIN_LENGTH })
          )
          .max(
            USERNAME_MAX_LENGTH,
            t("auth.usernameMaxLength", { max: USERNAME_MAX_LENGTH })
          )
          .matches(/^[a-zA-Z0-9]/, t("auth.usernameStartRule"))
          .matches(USERNAME_REGEX, t("auth.usernameCharsRule")),
      }),
    [t]
  );

  const formik = useFormik({
    initialValues: {
      username: instagramSuggestedUsername,
    },
    validationSchema: schema,
    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());
        const authProvider =
          typeof window !== "undefined"
            ? localStorage.getItem("auth_provider")
            : null;
        router.push(
          authProvider === "google" || authProvider === "instagram"
            ? "/register/fullname"
            : "/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 (
    <LocalePageShell>
      <AuthPageLayout>
        <form
          onSubmit={formik.handleSubmit}
          className="flex w-full flex-1 flex-col items-center"
        >
          <AuthPageContent>
            <AuthHead title={t("auth.usernameTitle")} />
            <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]">
                {t("auth.usernameHint", {
                  max: USERNAME_MAX_LENGTH,
                  min: USERNAME_MIN_LENGTH,
                })}
              </p>
              <AuthInput
                name="username"
                type="text"
                placeholder={t("auth.usernamePlaceholder")}
                dir="ltr"
                autoComplete="username"
                spellCheck={false}
                maxLength={USERNAME_MAX_LENGTH}
                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 &&
                instagramSuggestedUsername &&
                formik.values.username === instagramSuggestedUsername && (
                  <small className="text-gray-400 mt-2 block text-center text-xs">
                    {t("auth.usernameSuggestedFromInstagram")}
                  </small>
                )}

              {isDuplicate && (
                <small className="text-red-500 mt-2 block text-center font-medium">
                  {t("auth.usernameDuplicate")}
                </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">
                  {t("auth.usernameCharsRule")}
                </small>
              )}

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

          <AuthFormFooter>
            <AuthNextButton
              type="submit"
              loading={loading}
              disabled={
                loading || formik.values.username.length < USERNAME_MIN_LENGTH
              }
            >
              {t("auth.saveAndContinue")}
            </AuthNextButton>
          </AuthFormFooter>
        </form>
      </AuthPageLayout>
    </LocalePageShell>
  );
}

export default UsernamePage;
