"use client";

import * as React from "react";
import { cn } from "@/lib/utils";
import { removeLeadingZeros } from "@/lib/formatters";
import { Minus, Plus } from "lucide-react";

export interface QuantityInputProps
  extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "onChange" | "value" | "type"> {
  value: number | string | undefined;
  onChange: (value: number | undefined) => void;
  error?: boolean;
  /** 최소값 (기본: 0) */
  min?: number;
  /** 최대값 */
  max?: number;
  /** 증감 단위 (기본: 1) */
  step?: number;
  /** +/- 버튼 표시 (기본: false) */
  showButtons?: boolean;
  /** 단위 접미사 (개, EA, 박스 등) */
  suffix?: string;
  /** 빈 값 허용 (기본: true) */
  allowEmpty?: boolean;
}

/**
 * QuantityInput - 수량 입력 전용 컴포넌트
 *
 * 특징:
 * - 정수만 허용
 * - 기본 최소값 0 (음수 불가)
 * - 선택적 +/- 버튼
 * - 단위 접미사 지원
 * - Leading zero 자동 제거
 *
 * @example
 * // 기본
 * <QuantityInput value={qty} onChange={setQty} />
 *
 * // +/- 버튼 포함
 * <QuantityInput value={qty} onChange={setQty} showButtons />
 *
 * // 단위 표시
 * <QuantityInput value={qty} onChange={setQty} suffix="개" />
 *
 * // 범위 제한
 * <QuantityInput value={qty} onChange={setQty} min={1} max={100} />
 */
const QuantityInput = React.forwardRef<HTMLInputElement, QuantityInputProps>(
  (
    {
      className,
      value,
      onChange,
      error,
      min = 0,
      max,
      step = 1,
      showButtons = false,
      suffix,
      allowEmpty = true,
      disabled,
      onFocus,
      onBlur,
       
      defaultValue: _defaultValue, // controlled component이므로 defaultValue 무시
      ...props
    },
    ref
  ) => {
    const [isFocused, setIsFocused] = React.useState(false);
    const [displayValue, setDisplayValue] = React.useState<string>("");

    // 외부 value 변경 시 displayValue 동기화
    React.useEffect(() => {
      if (!isFocused) {
        if (value === undefined || value === null || value === "") {
          setDisplayValue("");
        } else {
          const numValue = typeof value === "string" ? parseInt(value, 10) : Math.floor(value);
          if (!isNaN(numValue)) {
            setDisplayValue(String(numValue));
          } else {
            setDisplayValue("");
          }
        }
      }
    }, [value, isFocused]);

    // 값 클램핑
    const clampValue = (num: number): number => {
      let result = num;
      if (min !== undefined && result < min) result = min;
      if (max !== undefined && result > max) result = max;
      return result;
    };

    // 입력값 정제
    const sanitizeInput = (input: string): string => {
      // 숫자만 허용
      let result = input.replace(/\D/g, "");
      // Leading zero 제거
      if (result) {
        result = removeLeadingZeros(result);
      }
      return result;
    };

    // 값을 숫자로 변환
    const parseValue = (input: string): number | undefined => {
      if (!input) {
        return allowEmpty ? undefined : min;
      }

      const num = parseInt(input, 10);
      if (isNaN(num)) {
        return allowEmpty ? undefined : min;
      }

      return clampValue(num);
    };

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
      const rawValue = e.target.value;
      const sanitized = sanitizeInput(rawValue);

      setDisplayValue(sanitized);

      const numValue = parseValue(sanitized);
      onChange(numValue);
    };

    const handleFocus = (e: React.FocusEvent<HTMLInputElement>) => {
      setIsFocused(true);
      onFocus?.(e);
    };

    const handleBlur = (e: React.FocusEvent<HTMLInputElement>) => {
      setIsFocused(false);

      const sanitized = sanitizeInput(displayValue);
      const numValue = parseValue(sanitized);

      onChange(numValue);

      if (numValue !== undefined) {
        setDisplayValue(String(numValue));
      } else {
        setDisplayValue("");
      }

      onBlur?.(e);
    };

    const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
      const allowedKeys = [
        "Backspace", "Delete", "Tab", "Escape", "Enter",
        "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown",
        "Home", "End"
      ];

      if (allowedKeys.includes(e.key)) return;

      // Ctrl/Cmd + A, C, V, X 허용
      if ((e.ctrlKey || e.metaKey) && ["a", "c", "v", "x"].includes(e.key.toLowerCase())) {
        return;
      }

      // 숫자만 허용
      if (/^\d$/.test(e.key)) return;

      e.preventDefault();
    };

    // +/- 버튼 핸들러
    const handleIncrement = () => {
      if (disabled) return;
      const currentValue = value !== undefined && value !== null && value !== ""
        ? (typeof value === "string" ? parseInt(value, 10) : Math.floor(value))
        : min;
      const newValue = clampValue((isNaN(currentValue) ? min : currentValue) + step);
      onChange(newValue);
    };

    const handleDecrement = () => {
      if (disabled) return;
      const currentValue = value !== undefined && value !== null && value !== ""
        ? (typeof value === "string" ? parseInt(value, 10) : Math.floor(value))
        : min;
      const newValue = clampValue((isNaN(currentValue) ? min : currentValue) - step);
      onChange(newValue);
    };

    const isAtMin = value !== undefined && typeof value === "number" && value <= min;
    const isAtMax = max !== undefined && value !== undefined && typeof value === "number" && value >= max;

    return (
      <div className={cn("relative flex items-center", showButtons && "gap-1")}>
        {/* 감소 버튼 */}
        {showButtons && (
          <button
            type="button"
            onClick={handleDecrement}
            disabled={disabled || isAtMin}
            className={cn(
              "flex h-9 w-9 items-center justify-center rounded-md border border-input bg-background text-sm font-medium transition-colors",
              "hover:bg-accent hover:text-accent-foreground",
              "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
              "disabled:pointer-events-none disabled:opacity-50"
            )}
          >
            <Minus className="h-4 w-4" />
          </button>
        )}

        <div className="relative flex-1">
          <input
            type="text"
            inputMode="numeric"
            ref={ref}
            data-slot="input"
            disabled={disabled}
            className={cn(
              "file:text-foreground placeholder:text-muted-foreground/50 selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base bg-input-background transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
              "focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
              error && "border-red-500 focus-visible:border-red-500 focus-visible:ring-red-500/20",
              showButtons && "text-center",
              suffix && !showButtons && "pr-10",
              className
            )}
            value={displayValue}
            onChange={handleChange}
            onFocus={handleFocus}
            onBlur={handleBlur}
            onKeyDown={handleKeyDown}
            {...props}
          />
          {/* 접미사 (버튼 없을 때만) */}
          {suffix && !showButtons && !isFocused && displayValue && (
            <span className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground text-sm pointer-events-none">
              {suffix}
            </span>
          )}
        </div>

        {/* 증가 버튼 */}
        {showButtons && (
          <button
            type="button"
            onClick={handleIncrement}
            disabled={disabled || isAtMax}
            className={cn(
              "flex h-9 w-9 items-center justify-center rounded-md border border-input bg-background text-sm font-medium transition-colors",
              "hover:bg-accent hover:text-accent-foreground",
              "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
              "disabled:pointer-events-none disabled:opacity-50"
            )}
          >
            <Plus className="h-4 w-4" />
          </button>
        )}
      </div>
    );
  }
);

QuantityInput.displayName = "QuantityInput";

export { QuantityInput };
