# PercentageInput

## Introduction

PercentageInput is a specialized numeric input for entering percentage values. It automatically appends a `%` suffix, formats numbers with thousand separators, and supports min/max validation with built-in error states. Use it for any field where users need to enter a percentage, such as tax rates, discounts, or commission rates.

> **Tip: Use built-in form props**
>
> This component supports `label` and `helperText` props directly. Use these instead of wrapping with FormControl + FormLabel + FormHelperText for simpler forms.

```tsx
<PercentageInput placeholder="Enter a percentage" />
```

| Field           | Description | Default |
| --------------- | ----------- | ------- |
| value           | —           | —       |
| defaultValue    | —           | —       |
| onChange        | —           | —       |
| name            | —           | —       |
| label           | —           | —       |
| disabled        | —           | —       |
| required        | —           | —       |
| error           | —           | —       |
| helperText      | —           | —       |
| useMinorUnit    | —           | —       |
| maxDecimalScale | —           | —       |
| min             | —           | —       |
| max             | —           | —       |

## Usage

```tsx
import { PercentageInput } from '@ceed/cds';

function MyComponent() {
  const [rate, setRate] = React.useState(0);

  return <PercentageInput label="Tax Rate" value={rate} onChange={(e) => setRate(e.target.value)} min={0} max={100} />;
}
```

## Sizes

PercentageInput supports three sizes: `sm`, `md` (default), and `lg`.

```tsx
<Stack gap={2}>
    <PercentageInput size="sm" label="Small" />
    <PercentageInput size="md" label="Medium" />
    <PercentageInput size="lg" label="Large" />
  </Stack>
```

## Form Features

### With Label

```tsx
<PercentageInput
  placeholder="Enter a percentage"
  label="Percentage Input"
/>
```

```tsx
<PercentageInput label="Discount Rate" />
```

### With Helper Text

```tsx
<PercentageInput
  placeholder="Enter a percentage"
  label="Percentage Input"
  helperText="Please enter a percentage"
/>
```

```tsx
<PercentageInput label="Commission" helperText="Enter the commission percentage." />
```

### Error State

```tsx
<PercentageInput
  placeholder="Enter a percentage"
  error
/>
```

### With Error Text

```tsx
<PercentageInput
  placeholder="Enter a percentage"
  label="Percentage Input"
  helperText="Please enter a percentage"
  error
/>
```

### Required

```tsx
<PercentageInput
  placeholder="Enter a percentage"
  label="Percentage Input"
  helperText="Please enter a percentage"
  required
/>
```

### Disabled

```tsx
<PercentageInput
  placeholder="Enter a percentage"
  disabled
/>
```

## Min / Max Validation

Set `min` and `max` to enforce value boundaries. When the entered value is outside the range, the input automatically shows an error state.

### Minimum Value

```tsx
<PercentageInput
  placeholder="Enter a percentage"
  label="Percentage Input"
  helperText="Please enter a percentage"
  min={10}
  defaultValue={5}
/>
```

```tsx
<PercentageInput min={10} defaultValue={5} />;
{
  /* Shows error because 5 < 10 */
}
```

### Maximum Value

```tsx
<PercentageInput
  placeholder="Enter a percentage"
  label="Percentage Input"
  helperText="Please enter a percentage"
  max={500}
  defaultValue={5000}
/>
```

```tsx
<PercentageInput max={500} defaultValue={5000} />;
{
  /* Shows error because 5000 > 500 */
}
```

## Decimal Scale

Use `maxDecimalScale` to control the number of decimal places allowed. The default is `0` (integers only).

```tsx
// Integer only (default)
<PercentageInput maxDecimalScale={0} />

// Up to 2 decimal places: 12.34%
<PercentageInput maxDecimalScale={2} />

// Up to 3 decimal places: 12.345%
<PercentageInput maxDecimalScale={3} />
```

## Minor Unit Mode

When `useMinorUnit` is `true`, the component converts between display values and minor units based on `maxDecimalScale`. This is useful when your API stores percentages in integer form.

```tsx
// Display shows "20.12%", onChange returns 20120
<PercentageInput useMinorUnit maxDecimalScale={3} value={20120} />

// Display shows "20.12%", onChange returns 20.12
<PercentageInput useMinorUnit={false} maxDecimalScale={2} value={20.12} />
```

## Common Use Cases

### Discount Configuration

```tsx
function DiscountSetting() {
  const [discount, setDiscount] = React.useState(0);

  return (
    <PercentageInput
      label="Discount"
      helperText="Enter 0-100%"
      value={discount}
      onChange={(e) => setDiscount(e.target.value)}
      min={0}
      max={100}
    />
  );
}
```

### Tax Rate Settings

```tsx
function TaxRateForm() {
  return (
    <Stack gap={2}>
      <PercentageInput label="VAT Rate" defaultValue={10} maxDecimalScale={2} min={0} max={100} />
      <PercentageInput label="Local Tax Rate" defaultValue={2.5} maxDecimalScale={2} min={0} max={50} />
    </Stack>
  );
}
```

### Progress / Completion Tracker

```tsx
function CompletionTracker({ value, onChange }) {
  return (
    <PercentageInput
      label="Completion"
      value={value}
      onChange={(e) => onChange(e.target.value)}
      min={0}
      max={100}
      helperText={value >= 100 ? 'Task is complete!' : `${100 - value}% remaining`}
    />
  );
}
```

## Best Practices

1. **Always set min and max**: Bound the valid range to prevent unreasonable values.

```tsx
// ✅ Clear bounds
<PercentageInput min={0} max={100} />

// ❌ Unbounded — user could enter 99999%
<PercentageInput />
```

2. **Use `maxDecimalScale` appropriately**: Set it to `0` for whole percentages (discounts, progress), or `2`–`3` for precise rates (tax, interest).

3. **Use `useMinorUnit` for API compatibility**: When your backend stores percentages as integers (e.g., 1050 for 10.50%), enable `useMinorUnit` with the appropriate `maxDecimalScale`.

4. **Provide context via labels and helper text**: Clarify what the percentage represents and what range is valid.

5. **Handle edge cases**: Consider what happens at boundary values (0%, 100%) and negative percentages if allowed.

## Props and Customization

### Key Props

| Prop              | Type                                                             | Default | Description                                            |
| ----------------- | ---------------------------------------------------------------- | ------- | ------------------------------------------------------ |
| `value`           | `number \| null`                                                 | -       | Percentage value (controlled mode)                     |
| `defaultValue`    | `number`                                                         | -       | Initial percentage value (uncontrolled mode)           |
| `onChange`        | `(event: { target: { name?, value?: number \| null } }) => void` | -       | Callback when the value changes                        |
| `useMinorUnit`    | `boolean`                                                        | `false` | When true, value is in basis points (e.g., 1000 = 10%) |
| `maxDecimalScale` | `number`                                                         | `0`     | Maximum number of decimal places                       |
| `min`             | `number`                                                         | -       | Minimum allowed percentage value                       |
| `max`             | `number`                                                         | -       | Maximum allowed percentage value                       |
| `label`           | `ReactNode`                                                      | -       | Form label displayed above the input                   |
| `helperText`      | `ReactNode`                                                      | -       | Helper text displayed below the input                  |
| `error`           | `boolean`                                                        | `false` | Applies danger color to indicate validation error      |
| `required`        | `boolean`                                                        | `false` | Marks the field as required                            |
| `disabled`        | `boolean`                                                        | `false` | Disables the input                                     |
| `name`            | `string`                                                         | -       | HTML name attribute for form submission                |
| `placeholder`     | `string`                                                         | -       | Placeholder text when the input is empty               |
| `size`            | `'sm' \| 'md' \| 'lg'`                                           | `'md'`  | Input size                                             |
| `sx`              | `SxProps`                                                        | -       | Custom styles using the MUI system                     |

> **Note**: For a **controlled** field that starts empty, pass `null` as `value`. Passing `undefined` makes the field uncontrolled from the first render, so later external updates (including resetting it to an empty value) are not reflected on screen.

> **Note**: PercentageInput also accepts all Input props and Framer Motion props.

## Accessibility

- The input has proper labeling via the `label` prop, linked with `aria-labelledby`.
- Error states trigger `aria-invalid` with associated error messages via `aria-describedby`.
- The `%` suffix is a visual decoration — ensure labels clarify that the field expects a percentage for screen readers.
- Min/max validation errors are communicated visually; add descriptive `helperText` to make the valid range clear.
