import { useState } from "react";
import styles from "./InlineNumber.module.css";

interface InlineNumberProps {
  value: number;
  onChange: (value: number) => void;
  className?: string;
  min?: number;
  max?: number;
}

export default function InlineNumber({
  value,
  onChange,
  className,
  min,
  max,
}: InlineNumberProps) {
  const [editing, setEditing] = useState(false);
  const [editValue, setEditValue] = useState("");

  function startEdit() {
    setEditValue(String(value));
    setEditing(true);
  }

  function commit() {
    setEditing(false);
    const num = parseInt(editValue, 10);
    if (isNaN(num)) return;
    const clamped = max !== undefined ? Math.min(num, max) : num;
    const final = min !== undefined ? Math.max(clamped, min) : clamped;
    if (final !== value) onChange(final);
  }

  function handleKeyDown(e: React.KeyboardEvent) {
    if (e.key === "Enter") commit();
    if (e.key === "Escape") setEditing(false);
  }

  if (editing) {
    return (
      <input
        className={styles.input}
        type="number"
        value={editValue}
        onChange={(e) => setEditValue(e.target.value)}
        onBlur={commit}
        onKeyDown={handleKeyDown}
        min={min}
        max={max}
        autoFocus
      />
    );
  }

  return (
    <span
      className={`${styles.value} ${className || ""}`}
      onClick={startEdit}
      title="Click to edit"
    >
      {value}
    </span>
  );
}
