# CurrencyInput

## Introduction

CurrencyInput is a specialized numeric input for entering monetary values. It automatically formats numbers with the appropriate currency symbol, thousand separators, and decimal places based on the selected currency (USD or KRW). It supports features like maximum value validation, minor unit conversion, and controlled/uncontrolled modes.

> **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
<CurrencyInput
  name="currency-input"
  defaultValue={1000}
/>
```

| Field        | Description | Default          |
| ------------ | ----------- | ---------------- |
| size         | —           | —                |
| name         | —           | "currency-input" |
| value        | —           | —                |
| defaultValue | —           | 1000             |
| currency     | —           | —                |
| label        | —           | —                |
| helperText   | —           | —                |
| required     | —           | —                |
| error        | —           | —                |
| disabled     | —           | —                |
| max          | —           | —                |
| useMinorUnit | —           | —                |
| onChange     | —           | —                |

## Usage

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

function MyComponent() {
  const [amount, setAmount] = React.useState(0);

  return <CurrencyInput label="Price" currency="USD" value={amount} onChange={(e) => setAmount(e.target.value)} />;
}
```

## Currency Formats

### USD (Default)

US Dollar format with `$` symbol, comma thousand separators, and 2 decimal places.

```tsx
<CurrencyInput
  name="currency-input"
  defaultValue={1000}
/>
```

### KRW

Korean Won format with `₩` symbol, comma thousand separators, and no decimal places.

```tsx
<CurrencyInput
  name="currency-input"
  defaultValue={1000}
  currency="KRW"
/>
```

```tsx
<CurrencyInput currency="KRW" value={50000} />
```

## Sizes

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

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

## Form Features

### With Label

```tsx
<CurrencyInput
  name="currency-input"
  defaultValue={1000}
  label="Currency Input"
/>
```

```tsx
<CurrencyInput label="Total Amount" />
```

### With Helper Text

```tsx
<CurrencyInput
  name="currency-input"
  defaultValue={1000}
  label="Currency Input"
  helperText="Please enter a currency"
/>
```

```tsx
<CurrencyInput label="Price" helperText="Enter the item price in USD." />
```

### Error State

```tsx
<CurrencyInput
  name="currency-input"
  defaultValue={1000}
  label="Currency Input"
  helperText="Please enter a currency"
  error
/>
```

```tsx
<CurrencyInput label="Amount" error helperText="Amount is required." />
```

## Price Limit

Set the `max` prop to enforce a maximum value. When the entered value exceeds the limit, the input automatically displays an error state with a formatted limit message.

```tsx
<CurrencyInput
  name="currency-input"
  defaultValue={10000000}
  label="Currency Input"
  helperText="Please enter a currency"
  max={1000000}
/>
```

```tsx
<CurrencyInput currency="USD" max={1000000} value={10000000} />
```

## Minor Unit Mode

When `useMinorUnit` is true, the component converts between display values and minor units (e.g., cents for USD). This is useful when your API stores amounts in the smallest currency unit.

```tsx
// Display shows "$10.00", but onChange returns 1000 (cents)
<CurrencyInput currency="USD" useMinorUnit value={1000} />

// Display shows "₩10,000", onChange returns 10000 (no conversion for KRW)
<CurrencyInput currency="KRW" useMinorUnit value={10000} />
```

## Common Use Cases

### Product Price Editor

```tsx
function ProductPriceEditor() {
  const [priceUSD, setPriceUSD] = React.useState(0);
  const [priceKRW, setPriceKRW] = React.useState(0);

  return (
    <Stack gap={2}>
      <CurrencyInput
        label="USD Price"
        currency="USD"
        value={priceUSD}
        onChange={(e) => setPriceUSD(e.target.value)}
        max={99999.99}
      />
      <CurrencyInput
        label="KRW Price"
        currency="KRW"
        value={priceKRW}
        onChange={(e) => setPriceKRW(e.target.value)}
        max={99999999}
      />
    </Stack>
  );
}
```

### Invoice Line Item

```tsx
function InvoiceLineItem({ item, onChange }) {
  return (
    <Stack direction="row" gap={2} alignItems="flex-end">
      <Input label="Description" value={item.description} />
      <CurrencyInput
        label="Unit Price"
        currency="USD"
        value={item.unitPrice}
        onChange={(e) => onChange({ ...item, unitPrice: e.target.value })}
      />
      <Input label="Qty" type="number" value={item.quantity} sx={{ width: 80 }} />
    </Stack>
  );
}
```

### Budget Limit Input

```tsx
function BudgetSetting() {
  const [budget, setBudget] = React.useState(50000);

  return (
    <CurrencyInput
      label="Monthly Budget"
      helperText="Set the maximum monthly spending limit."
      currency="USD"
      value={budget}
      onChange={(e) => setBudget(e.target.value)}
      max={1000000}
    />
  );
}
```

## Controlled Empty Value

Whether a field is controlled is decided **once, on mount** — the same convention MUI's `useControlled` follows. A field that mounts with `value={undefined}` is treated as uncontrolled for its whole lifetime, so later updates from the parent never reach the screen.

Pass `null` to express "controlled, but currently empty":

```tsx
import { useState } from 'react';
import { Button, CurrencyInput, Stack } from '@ceed/cds';

function AmountField() {
  const [amount, setAmount] = useState<number | null>(null);

  return (
    <Stack gap={2}>
      <CurrencyInput label="Amount" value={amount} onChange={(e) => setAmount(e.target.value)} />
      {/* Clears the input on screen, not just in state. */}
      <Button onClick={() => setAmount(null)}>Reset</Button>
    </Stack>
  );
}
```

Form libraries are where this bites. When something outside the input empties the state — `react-hook-form`'s `setValue('amount', undefined)`, for instance — `value={field.value ?? null}` is what carries that back to the screen.

`onChange` reports an empty field as `null` too, so the value it hands you can go straight back into `value` without a conversion step. Typing the state as `number | null` and seeding it with `null` is the shape that needs no `??` anywhere.

## Best Practices

1. **Choose the right currency**: Always set the `currency` prop explicitly. USD uses 2 decimal places while KRW uses none.

```tsx
// ✅ Explicit currency
<CurrencyInput currency="USD" />
<CurrencyInput currency="KRW" />

// ❌ Relying on default — may confuse users expecting KRW
<CurrencyInput />
```

2. **Set max limits**: Use `max` to prevent unreasonable values. The component displays a helpful error message when the limit is exceeded.

3. **Use `useMinorUnit` for API integration**: When your backend stores amounts in minor units (cents, etc.), enable `useMinorUnit` to avoid manual conversion.

4. **Use built-in label and helperText**: Prefer the component's own `label` and `helperText` props over wrapping with FormControl.

5. **Handle negative values carefully**: CurrencyInput supports negative values. If negatives are not valid for your use case, validate in `onChange`.

## Props and Customization

### Key Props

| Prop           | Type                                                             | Default | Description                                                              |
| -------------- | ---------------------------------------------------------------- | ------- | ------------------------------------------------------------------------ |
| `value`        | `number \| null`                                                 | -       | Currency value (controlled mode)                                         |
| `defaultValue` | `number`                                                         | -       | Initial currency value (uncontrolled mode)                               |
| `onChange`     | `(event: { target: { name?, value?: number \| null } }) => void` | -       | Callback when the value changes                                          |
| `currency`     | `'USD' \| 'KRW' \| 'CAD' \| 'usd' \| 'krw' \| 'cad'`             | `'USD'` | Currency code (uppercase or lowercase; determines symbol and formatting) |
| `useMinorUnit` | `boolean`                                                        | `false` | When true, value is in minor units (e.g., cents for USD)                 |
| `max`          | `number`                                                         | -       | Maximum allowed 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.

## Accessibility

- The input has `role="textbox"` with proper labeling via the `label` prop.
- Error states are communicated via `aria-invalid` and associated error messages.
- The currency symbol serves as a visual indicator; ensure labels also mention the currency for screen readers.
- Keyboard input is fully supported — users can type numbers, and formatting is applied automatically.
