"use client";

import {
  forwardRef,
  useCallback,
  useEffect,
  useId,
  useImperativeHandle,
  useRef,
  useState,
} from "react";
import type { FocusEvent, FormEvent } from "react";

export type ActiveAnswerInput = 0 | 1;

const ANSWER_INPUT_PATTERN = /^-?\d*(?:\.\d*)?$/;
const DESKTOP_INPUT_DEVICE_QUERY = "(any-hover: hover) and (any-pointer: fine)";
const KEYPAD_KEYS = [
  "1",
  "2",
  "3",
  "4",
  "5",
  "6",
  "7",
  "8",
  "9",
  "+/-",
  "0",
];

export interface AnswerFormHandle {
  focusInput: () => void;
}

interface AnswerFormProps {
  answerA: string;
  answerB: string;
  activeInput: ActiveAnswerInput;
  error: string;
  onAnswerAChange: (value: string) => void;
  onAnswerBChange: (value: string) => void;
  onActiveInputChange: (input: ActiveAnswerInput) => void;
  onInputBlur?: () => void;
  onInputFocus?: () => void;
  onSubmit: (event: FormEvent<HTMLFormElement>) => void;
}

const AnswerForm = forwardRef<AnswerFormHandle, AnswerFormProps>(function AnswerForm(
  {
    answerA,
    answerB,
    activeInput,
    error,
    onAnswerAChange,
    onAnswerBChange,
    onActiveInputChange,
    onInputBlur,
    onInputFocus,
    onSubmit,
  },
  ref,
) {
  const inputId = useId();
  const formRef = useRef<HTMLFormElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);
  const blurTimeoutRef = useRef<number | null>(null);
  const [keypadOpen, setKeypadOpen] = useState(false);
  const [desktopInputDevice, setDesktopInputDevice] = useState(false);

  const activeAnswer = activeInput === 0 ? answerA : answerB;
  const activeLabel = activeInput === 0 ? "첫째 항" : "둘째 항";
  const activeEnterKeyHint = activeInput === 0 ? "next" : "done";
  const activeAnswerChange =
    activeInput === 0 ? onAnswerAChange : onAnswerBChange;

  function updateAnswer(value: string) {
    if (!ANSWER_INPUT_PATTERN.test(value)) return;

    activeAnswerChange(value);
  }

  function handleInputFocus() {
    if (blurTimeoutRef.current !== null) {
      window.clearTimeout(blurTimeoutRef.current);
      blurTimeoutRef.current = null;
    }

    setKeypadOpen(true);
    onInputFocus?.();
  }

  function handleInputBlur(event: FocusEvent<HTMLInputElement>) {
    const nextFocusedElement = event.relatedTarget;

    if (
      nextFocusedElement instanceof Node &&
      formRef.current?.contains(nextFocusedElement)
    ) {
      return;
    }

    blurTimeoutRef.current = window.setTimeout(() => {
      blurTimeoutRef.current = null;

      if (formRef.current?.contains(document.activeElement)) {
        setKeypadOpen(true);
        return;
      }

      setKeypadOpen(false);
      onInputBlur?.();
    }, 0);
  }

  const focusInput = useCallback(() => {
    const input = inputRef.current;

    if (!input) return;

    const wasFocused = document.activeElement === input;

    input.focus({ preventScroll: true });

    if (wasFocused) {
      onInputFocus?.();
    }
  }, [onInputFocus]);

  useImperativeHandle(ref, () => ({ focusInput }), [focusInput]);

  useEffect(() => {
    const mediaQuery = window.matchMedia(DESKTOP_INPUT_DEVICE_QUERY);
    const updateInputDevice = () => {
      setDesktopInputDevice(mediaQuery.matches);
    };

    updateInputDevice();
    mediaQuery.addEventListener("change", updateInputDevice);

    return () => {
      if (blurTimeoutRef.current !== null) {
        window.clearTimeout(blurTimeoutRef.current);
      }
      mediaQuery.removeEventListener("change", updateInputDevice);
    };
  }, []);

  function setAnswer(input: ActiveAnswerInput, value: string) {
    if (input === 0) {
      onAnswerAChange(value);
    } else {
      onAnswerBChange(value);
    }
  }

  function toggleMinus() {
    activeAnswerChange(
      activeAnswer.startsWith("-") ? activeAnswer.slice(1) : `-${activeAnswer}`,
    );
    focusInput();
  }

  function appendKeypadValue(value: string) {
    updateAnswer(`${activeAnswer}${value}`);
    focusInput();
  }

  function deleteLastCharacter() {
    updateAnswer(activeAnswer.slice(0, -1));
    focusInput();
  }

  function moveToInput(input: ActiveAnswerInput, reset = false) {
    onActiveInputChange(input);
    if (reset) {
      setAnswer(input, "");
    }
    focusInput();
  }

  function handleEnter() {
    if (activeInput === 0) {
      moveToInput(1);
      return;
    }

    formRef.current?.requestSubmit();
    focusInput();
  }

  const answerButtons = [
    {
      index: 0 as const,
      label: "첫째 항",
      value: answerA,
    },
    {
      index: 1 as const,
      label: "둘째 항",
      value: answerB,
    },
  ];

  return (
    <form
      ref={formRef}
      onSubmit={onSubmit}
      className="rounded-md bg-white p-6 shadow-sm ring-1 ring-slate-200 sm:p-8"
    >
      <div className="flex flex-col gap-4">
        <div>
          <label
            htmlFor={inputId}
            className="mb-2 block text-sm font-semibold text-slate-700"
          >
            {activeLabel}
          </label>
          <input
            id={inputId}
            ref={inputRef}
            type="text"
            value={activeAnswer}
            onFocus={handleInputFocus}
            onBlur={handleInputBlur}
            onChange={(event) => updateAnswer(event.target.value)}
            onKeyDown={(event) => {
              if (event.key === "Enter") {
                event.preventDefault();
                handleEnter();
              }
            }}
            autoComplete="off"
            enterKeyHint={activeEnterKeyHint}
            inputMode="none"
            pattern="-?[0-9]*(\.[0-9]*)?"
            className="h-12 w-full min-w-0 rounded-md border border-slate-300 bg-white px-3 text-lg font-semibold text-slate-950 outline-none transition focus:border-emerald-600 focus:ring-2 focus:ring-emerald-200 sm:px-4"
          />
        </div>

        <div
          className="inline-flex w-fit max-w-full gap-1 rounded-md border border-slate-300 bg-white p-1 shadow-sm"
          role="group"
          aria-label="입력 항 선택"
        >
          {answerButtons.map((button) => {
            const selected = activeInput === button.index;

            return (
              <button
                key={button.index}
                type="button"
                onPointerDown={(event) => event.preventDefault()}
                onClick={() => moveToInput(button.index, true)}
                aria-pressed={selected}
                aria-label={`${button.label} 다시 입력`}
                className={`inline-flex h-10 min-w-20 items-center justify-center rounded px-3 text-base font-semibold transition focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2 ${
                  selected
                    ? "bg-emerald-700 text-white"
                    : "text-slate-700 hover:bg-slate-100"
                }`}
              >
                {button.value || "?"}
              </button>
            );
          })}
        </div>

        {keypadOpen && !desktopInputDevice ? (
          <div
            className="grid grid-cols-3 gap-2"
            role="group"
            aria-label={`${activeLabel} 숫자 입력 키패드`}
          >
            {KEYPAD_KEYS.map((key) => (
              <button
                key={key}
                type="button"
                onPointerDown={(event) => event.preventDefault()}
                onClick={() =>
                  key === "+/-" ? toggleMinus() : appendKeypadValue(key)
                }
                aria-label={
                  key === "+/-"
                    ? `${activeLabel} 양수 음수 기호 전환`
                    : `${activeLabel} 숫자 ${key} 입력`
                }
                className="inline-flex h-12 items-center justify-center rounded-md border border-slate-300 bg-white text-lg font-semibold text-slate-900 shadow-sm transition hover:bg-slate-100 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2"
              >
                {key}
              </button>
            ))}
            <button
              type="button"
              onPointerDown={(event) => event.preventDefault()}
              onClick={deleteLastCharacter}
              aria-label={`${activeLabel} 마지막 글자 삭제`}
              className="inline-flex h-12 items-center justify-center rounded-md border border-slate-300 bg-white text-xl font-semibold text-slate-800 shadow-sm transition hover:bg-slate-100 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2"
            >
              ⌫
            </button>
            <button
              type="button"
              onPointerDown={(event) => event.preventDefault()}
              onClick={() => appendKeypadValue(".")}
              aria-label={`${activeLabel} 소수점 입력`}
              className="inline-flex h-12 items-center justify-center rounded-md border border-slate-300 bg-white text-lg font-semibold text-slate-900 shadow-sm transition hover:bg-slate-100 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2"
            >
              .
            </button>
            <button
              type="button"
              onPointerDown={(event) => event.preventDefault()}
              onClick={handleEnter}
              aria-label={
                activeInput === 0
                  ? "첫째 항 입력 완료 후 둘째 항으로 이동"
                  : "둘째 항 입력 완료 후 제출"
              }
              className="col-span-2 inline-flex h-12 items-center justify-center rounded-md bg-emerald-700 text-base font-semibold text-white shadow-sm transition hover:bg-emerald-800 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2"
            >
              ↵
            </button>
          </div>
        ) : null}
      </div>

      {error ? (
        <p className="mt-3 text-sm font-semibold text-red-700">{error}</p>
      ) : null}
    </form>
  );
});

export default AnswerForm;
