"use client"
import React, { ElementRef, forwardRef } from "react"
import { Add, Remove } from "../../icons"
import { disabledVariants, interactiveVariants } from "../../styles"
import { classNames } from "../../utils"
import { Input, InputProps } from "../Input"
import { UnstyledButton } from "../UnstyledButton"

export type QuantityInputProps = Omit<
  InputProps,
  "startEnhancer" | "endEnhancer" | "min" | "max" | "value"
> & {
  min?: number
  max?: number
  value: number | undefined | null
  onValueChange: (
    value: number | null,
    source: "increment" | "decrement" | "input",
  ) => void
}

export const QuantityInput = forwardRef<ElementRef<"div">, QuantityInputProps>(
  function QuantityInput(
    { className, disabled, min, max, onChange, onValueChange, value, ...rest },
    ref,
  ) {
    const effectiveValue = value || 0
    const isIncrementDisabled =
      disabled || Boolean(max !== undefined && effectiveValue >= max)
    const isDecrementDisabled =
      disabled || Boolean(min !== undefined && effectiveValue <= min)

    return (
      <Input
        className={classNames(
          "w-[116px] px-2.5 font-mono [&_input]:text-center",
          className,
        )}
        disabled={disabled}
        endEnhancer={
          <UnstyledButton
            className={classNames(
              interactiveVariants({ text: "primary" }),
              disabledVariants({
                disabled: isIncrementDisabled,
              }),
            )}
            disabled={isIncrementDisabled}
            onClick={e => {
              const newValue = effectiveValue + 1
              onValueChange(Math.min(newValue, max || newValue), "increment")
              e.stopPropagation()
            }}
          >
            <Add size={16} />
          </UnstyledButton>
        }
        max={max}
        min={min}
        ref={ref}
        startEnhancer={
          <UnstyledButton
            className={classNames(
              interactiveVariants({ text: "primary" }),
              disabledVariants({
                disabled: isDecrementDisabled,
              }),
            )}
            disabled={isDecrementDisabled}
            onClick={e => {
              const newValue = effectiveValue - 1
              onValueChange(Math.max(newValue, min || newValue), "decrement")
              e.stopPropagation()
            }}
          >
            <Remove size={16} />
          </UnstyledButton>
        }
        type="number"
        value={value ?? ""}
        onChange={e => {
          onValueChange(e.target.value ? Number(e.target.value) : null, "input")
          onChange?.(e)
        }}
        {...rest}
      />
    )
  },
)
