"use client";

import cx from "classnames";
import React from "react";

import { useStatic } from "../../../utils/hooks";
import { TextInput } from "../TextInput/TextInput";

import InputStepperStatic from "./InputStepper.static";

const CLASS_ROOT = "input-stepper";

export interface InputStepperConfig {
  min?: number;
  max?: number;
  defaultValue?: number;
  nonEditableInput?: boolean;
}

export interface InputStepperProps {
  config?: InputStepperConfig;
  id: string;
  inputClassName?: string;
  isDisabled?: boolean;
  /** Invalid state */
  isInvalid?: boolean;
  name?: string;
  nonEditableInput?: boolean;
  className?: string;
  [key: string]: any;
}

const InputStepper: React.FC<InputStepperProps> = ({
  className,
  inputClassName,
  id,
  config,
  isDisabled,
  isInvalid,
  nonEditableInput = false,
  ...other
}) => {
  const [elementRef] = useStatic(InputStepperStatic, {
    nonEditableInput,
  });

  const { name = id, ...props } = other;

  const classes = cx(`${CLASS_ROOT}__field`, inputClassName);

  return (
    <div
      className={cx(CLASS_ROOT, className, {
        [`${CLASS_ROOT}--disabled`]: isDisabled,
        [`${CLASS_ROOT}--invalid`]: isInvalid,
      })}
      ref={elementRef}
      data-inputstepper={config ? JSON.stringify(config) : true}
      {...props}
    >
      <button
        disabled={isDisabled}
        className={`${CLASS_ROOT}__button ${CLASS_ROOT}__button--minus`}
        aria-label="znížiť počet"
      ></button>
      {nonEditableInput || config?.nonEditableInput ? (
        <p id={id} className={`${CLASS_ROOT}__number`}></p>
      ) : (
        <TextInput
          className={classes}
          id={id}
          name={name}
          disabled={isDisabled}
          isInvalid={isInvalid}
          htmlType="number"
          inputMode="numeric"
        />
      )}
      <button
        disabled={isDisabled}
        className={`${CLASS_ROOT}__button ${CLASS_ROOT}__button--plus`}
        aria-label="zvýšiť počet"
      ></button>
    </div>
  );
};

InputStepper.displayName = "InputStepper";

export { InputStepper };
