"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import {
  EMPTY_NICKNAME_AVAILABILITY,
  type NicknameAvailability,
} from "@/features/shared/nicknameAvailability";
import type { ApiResponse } from "@/lib/api/types";
import type { SaveMutation } from "@/features/shared/saveMutation";
import type {
  CheckUserQuery,
  CheckUserResult,
} from "@/features/auth/services/authApi";
import { logRequestError } from "@/lib/api/logError";

/**
 * Whether a typed nickname is still free.
 *
 * Debounced through a ref rather than `useDebouncedValue` because the check is a
 * *request*, not a derived value: the timer has to be cancellable from the
 * caller, and an in-flight check for an old nickname must not overwrite the
 * answer for the current one.
 *
 * `null` means "not checked yet" and is deliberately distinct from `false`: the
 * validation rule only rejects on an explicit `false`, so a nickname the server
 * has not answered for yet never blocks the form.
 */
interface NicknameAvailabilityContext {
  /** `POST /check-user/` — answers whether a nickname is taken. */
  checkUserMutation: SaveMutation<
    CheckUserQuery,
    ApiResponse<CheckUserResult>
  >;
  /** The saved nickname — re-typing it is not a conflict with oneself. */
  t: (key: string, options?: Record<string, unknown>) => string;
}

export function useNicknameAvailability(context: NicknameAvailabilityContext) {
  const { checkUserMutation, t } = context;
  /*
   * `mutateAsync` hoisted out of the mutation object on purpose.
   *
   * React Query keeps this function referentially stable while the mutation
   * object changes identity on every status transition. Depending on the object
   * would rebuild the debounced callback below mid-keystroke and reset its wait;
   * depending on the hoisted function is both stable and complete, so the
   * dependency list is honest rather than suppressed. This replaces an
   * `eslint-disable-next-line react-hooks/exhaustive-deps` whose only missing
   * dependency was `checkUserMutation` — verified by removing the directive and
   * reading what the rule actually reported.
   */
  const checkUserAsync = checkUserMutation.mutateAsync;
  const [nicknameAvailability, setNicknameAvailability] = useState<NicknameAvailability>(
    EMPTY_NICKNAME_AVAILABILITY
  );
  const nicknameCheckTimeoutRef = useRef<NodeJS.Timeout | null>(null);

  const checkNicknameAvailability = useCallback(
    async (nickname: string, currentNickname: string) => {
      if (nicknameCheckTimeoutRef.current) {
        clearTimeout(nicknameCheckTimeoutRef.current);
      }

      if (!nickname || nickname.trim() === "" || nickname === currentNickname) {
        setNicknameAvailability({
          checking: false,
          available: null,
          message: "",
        });
        return;
      }

      const nicknameRegex = /^[A-Za-z0-9._]+$/;
      if (!nicknameRegex.test(nickname)) {
        setNicknameAvailability({
          checking: false,
          available: null,
          message: "",
        });
        return;
      }

      setNicknameAvailability({ checking: true, available: null, message: "" });

      nicknameCheckTimeoutRef.current = setTimeout(async () => {
        try {
          const response = await checkUserAsync({
            nickname: nickname.trim(),
          });

          /* `?? null`: the response only carries a `nickname` branch when
             one was asked about, so this can be absent. `null` is the
             "not answered" state the UI already treats as not-available —
             `undefined` was the same at runtime but not in the type. */
          const isAvailable = response?.data?.nickname?.is_new_user ?? null;

          setNicknameAvailability({
            checking: false,
            available: isAvailable,
            message: isAvailable
              ? t("COMMON.USERNAME_AVAILABLE")
              : t("COMMON.USERNAME_TAKEN"),
          });
        } catch (error) {
          logRequestError("Error checking nickname:", error);
          setNicknameAvailability({
            checking: false,
            available: null,
            message: "",
          });
        }
      }, 500);
    },
    [t, checkUserAsync]
  );

  useEffect(() => {
    return () => {
      if (nicknameCheckTimeoutRef.current) {
        clearTimeout(nicknameCheckTimeoutRef.current);
      }
    };
  }, []);

  return { nicknameAvailability, checkNicknameAvailability };
}
