import { useCallback, useEffect, useRef } from "react";
import { applyTitleLimit, TITLE_MAX_LENGTH } from "@/shared/lib/title";

interface UseTitleInputOptions {
  value: string;
  onChange: (value: string) => void;
  onCommit?: (value: string) => void;
  maxLength?: number;
}

export const useTitleInput = ({
  value,
  onChange,
  onCommit,
  maxLength = TITLE_MAX_LENGTH,
}: UseTitleInputOptions) => {
  const isComposingRef = useRef(false);
  const committedRef = useRef(value);

  useEffect(() => {
    if (isComposingRef.current) return;
    committedRef.current = value;
  }, [value]);

  const commitValue = useCallback(
    (nextValue: string) => {
      committedRef.current = nextValue;
      onChange(nextValue);
      onCommit?.(nextValue);
    },
    [onChange, onCommit]
  );

  const handleChange = useCallback(
    (nextValue: string) => {
      if (isComposingRef.current) {
        onChange(nextValue);
        return;
      }
      const limited = applyTitleLimit(committedRef.current, nextValue, maxLength);
      commitValue(limited);
    },
    [maxLength, onChange, commitValue]
  );

  const handleCompositionStart = useCallback(() => {
    isComposingRef.current = true;
  }, []);

  const handleCompositionEnd = useCallback(
    (nextValue: string) => {
      isComposingRef.current = false;
      const limited = applyTitleLimit(committedRef.current, nextValue, maxLength);
      commitValue(limited);
    },
    [maxLength, commitValue]
  );

  return {
    handleChange,
    handleCompositionStart,
    handleCompositionEnd,
    commitValue,
    maxLength,
  };
};
