import React, { useState } from "react";
import { Input } from '@komi-app/components';


import { noop } from "../../../utils/fns";

import classnames from "classnames";
import "../RuleBlock.scss";
import { RulePill } from "../../RulePill";

export interface NumericRuleBlockProps extends React.HTMLProps<HTMLDivElement> {
  value?: number;
  onValueChange?: (value: number) => void;
}
export const NumericRuleBlock: React.FC<NumericRuleBlockProps> = ({
  value = 1,
  onValueChange = noop,
  ...props
}) => {
  const [isInputVisible, setIsInputVisible] = useState(false);

  const toggleActive = () => setIsInputVisible((prevState) => !prevState);

  const handleKeyDown: React.KeyboardEventHandler<HTMLInputElement> = ({ key }) => {
    if (key === "Enter") {
      setIsInputVisible(false);
    }
  };
  const handleNumericValueChange = (value: string) => {
    const numericValue = Number(value || 0);
    onValueChange(numericValue);
  };

  const classNames = classnames(
    {
      "rule-block-number__input": isInputVisible,
      "rule-block__pill rule-block-number__pill": !isInputVisible,
    },
    props.className,
  );

  return isInputVisible ? (
    <Input
      characterRegex={/[0-9]/}
      className={classNames}
      onKeyDown={handleKeyDown}
      onValueChange={handleNumericValueChange}
      onBlur={() => setIsInputVisible(false)}
      value={String(value)}
      autoFocus
    />
  ) : (
    <RulePill
      className={classNames}
      isActive={false}
      onClick={toggleActive}
      value={String(value)}
    />
  );
};
