# MonthPicker

## Introduction

MonthPicker is a form input component that allows users to select a specific month and year from a calendar popup. Unlike DatePicker which provides day-level selection, MonthPicker focuses on month-level granularity and displays months in a grid format for quick selection.

It is ideal for scenarios like billing periods, report months, subscription dates, or any use case where day-level precision is unnecessary. The component supports multiple value formats and display formats, controlled and uncontrolled modes, and date range constraints.

```tsx
<MonthPicker />
```

| Field         | Description | Default |
| ------------- | ----------- | ------- |
| value         | —           | —       |
| defaultValue  | —           | —       |
| name          | —           | —       |
| disabled      | —           | —       |
| inputReadOnly | —           | —       |
| readOnly      | —           | —       |
| required      | —           | —       |
| label         | —           | —       |
| error         | —           | —       |
| helperText    | —           | —       |
| minDate       | —           | —       |
| maxDate       | —           | —       |
| disableFuture | —           | —       |
| disablePast   | —           | —       |
| format        | —           | —       |
| onChange      | —           | —       |

## Usage

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

function MonthForm() {
  const [month, setMonth] = useState('');

  return <MonthPicker label="Select Month" value={month} onChange={(e) => setMonth(e.target.value)} />;
}
```

> 💡 **Use built-in form props**
>
> This component natively supports form elements such as `label` and `helperText` props.
> When building forms, use these built-in props instead of manually composing labels and helper text with Typography.

## Sizes

MonthPicker supports three sizes (`sm`, `md`, `lg`) for different layouts and contexts.

```tsx
<Stack gap={2}>
    <MonthPicker size="sm" />
    <MonthPicker size="md" />
    <MonthPicker size="lg" />
  </Stack>
```

## Form Field Features

### With Label

Add a label above the month picker to indicate the field purpose.

```tsx
<MonthPicker label="Date" />
```

### With Helper Text

Provide additional guidance below the input to help users understand the expected selection.

```tsx
<MonthPicker
  label="Date"
  helperText="Please select a date"
/>
```

### Required Field

Mark the field as required in forms. An asterisk indicator is displayed alongside the label.

```tsx
<MonthPicker
  label="Label"
  helperText="I'm helper text"
  required
/>
```

### Error State

Display validation errors with error styling applied to the input, label, and helper text.

```tsx
<MonthPicker
  label="Date"
  helperText="Please select a date"
  error
/>
```

### Disabled

Prevent user interaction when the picker is disabled.

```tsx
<MonthPicker disabled />
```

## Input Read Only Calendar Selection

Set `inputReadOnly` to prevent keyboard typing while allowing month selection from the calendar. Clicking either the input or the calendar button toggles the popup, matching DatePicker's `inputReadOnly` behavior. Users can still select a month or clear the value from the calendar.

```tsx
<MonthPicker inputReadOnly label="Select Month" defaultValue="2024/04/01" />
```

```tsx
<MonthPicker
  defaultValue="2024/04/01"
  inputReadOnly
  name="month"
  locale="en-US"
  onChange={fn()}
/>
```

## Read Only MonthPicker

Set `readOnly` to display a value without allowing changes. It blocks typing and prevents the calendar from opening through either the input or the calendar button, even when `inputReadOnly` is also enabled. Use `inputReadOnly` when users should still be able to select a month.

```tsx
<MonthPicker
  defaultValue="2024/04/01"
  readOnly
  inputReadOnly
  onChange={fn()}
/>
```

## Disabled Input Read Only MonthPicker

The `disabled` prop prevents all interaction, including opening the calendar when `inputReadOnly` is enabled.

```tsx
<MonthPicker
  defaultValue="2024/04/01"
  inputReadOnly
  disabled
  onChange={fn()}
/>
```

## Date Constraints

### Minimum Date

Restrict selection to months on or after a minimum date. Months before the limit are visually disabled.

```tsx
<MonthPicker minDate="2024-04-10" />
```

### Maximum Date

Restrict selection to months on or before a maximum date. Months after the limit are visually disabled.

```tsx
<MonthPicker maxDate="2024-04-10" />
```

### Disable Future

Prevent selection of any month in the future, relative to the current date.

```tsx
<MonthPicker disableFuture />
```

### Disable Past

Prevent selection of any month in the past, relative to the current date.

```tsx
<MonthPicker disablePast />
```

## Controlled vs Uncontrolled

### Controlled

The parent component manages the month state via the `value` and `onChange` props. External buttons or logic can programmatically update the selected value.

```tsx
<Stack gap={2}>
    <MonthPicker {...args} value={value} onChange={(e) => setValue(e.target.value)} />
    <Button
      onClick={() => {
        const currentValue = new Date(value);
        currentValue.setMonth(currentValue.getMonth() + 1);
        const year = currentValue.getFullYear();
        const month = String(currentValue.getMonth() + 1).padStart(2, "0");
        setValue(`${year}/${month}/01`);
      }}
    >
      Next Month
    </Button>
  </Stack>
```

### Uncontrolled

The component manages its own state internally using `defaultValue`. The parent can still listen for changes via `onChange`.

```tsx
<MonthPicker
  label="Uncontrolled MonthPicker"
  helperText="Please select a date"
  defaultValue="2024/04/01"
/>
```

## Formats

### Value Formats

The `format` prop determines the shape of the value emitted by `onChange`. Each format includes a day component (set to `01`). The display always defaults to `YYYY/MM` unless `displayFormat` is also set.

```tsx
<Stack gap={2}>
    <MonthPicker
      {...args}
      value={value["YYYY.MM.DD"]}
      label="YYYY.MM.DD"
      name="YYYY.MM.DD"
      format="YYYY.MM.DD"
      onChange={handleChange}
    />
    <MonthPicker
      {...args}
      value={value["YYYY/MM/DD"]}
      label="YYYY/MM/DD"
      name="YYYY/MM/DD"
      format="YYYY/MM/DD"
      onChange={handleChange}
    />
    <MonthPicker
      {...args}
      value={value["MM/DD/YYYY"]}
      label="MM/DD/YYYY"
      name="MM/DD/YYYY"
      format="MM/DD/YYYY"
      onChange={handleChange}
    />
    <MonthPicker
      {...args}
      value={value["YYYY-MM-DD"]}
      label="YYYY-MM-DD"
      name="YYYY-MM-DD"
      format="YYYY-MM-DD"
      onChange={handleChange}
    />
    <MonthPicker
      {...args}
      value={value["DD/MM/YYYY"]}
      label="DD/MM/YYYY"
      name="DD/MM/YYYY"
      format="DD/MM/YYYY"
      onChange={handleChange}
    />
    <MonthPicker
      {...args}
      value={value["DD.MM.YYYY"]}
      label="DD.MM.YYYY"
      name="DD.MM.YYYY"
      format="DD.MM.YYYY"
      onChange={handleChange}
    />
  </Stack>
```

### Display Formats

The `displayFormat` prop controls what users see in the input field, independent of the underlying value format. Supports the special token `MMMM` for full month names.

```tsx
<Stack gap={2}>
    <MonthPicker
      {...args}
      value={value1}
      label="YYYY.MM"
      name="YYYY.MM"
      displayFormat="YYYY.MM"
      onChange={(e) => {
        setValue1(e.target.value);
        args.onChange?.(e);
      }}
    />
    <MonthPicker
      {...args}
      value={value2}
      label="YYYY/MM"
      name="YYYY/MM"
      displayFormat="YYYY/MM"
      onChange={(e) => {
        setValue2(e.target.value);
        args.onChange?.(e);
      }}
    />
    <MonthPicker
      {...args}
      value={value3}
      label="MM/YYYY"
      name="MM/YYYY"
      displayFormat="MM/YYYY"
      onChange={(e) => {
        setValue3(e.target.value);
        args.onChange?.(e);
      }}
    />
    <MonthPicker
      {...args}
      value={value4}
      label="YYYY-MM"
      name="YYYY-MM"
      displayFormat="YYYY-MM"
      onChange={(e) => {
        setValue4(e.target.value);
        args.onChange?.(e);
      }}
    />
    <MonthPicker
      {...args}
      value={value5}
      label="YYYY-MM-DD"
      name="YYYY-MM-DD"
      displayFormat="YYYY-MM-DD"
      onChange={(e) => {
        setValue5(e.target.value);
        args.onChange?.(e);
      }}
    />
    <MonthPicker
      {...args}
      value={value6}
      label="MMMM YYYY"
      name="MMMM YYYY"
      displayFormat="MMMM YYYY"
      onChange={(e) => {
        setValue6(e.target.value);
        args.onChange?.(e);
      }}
    />
    <MonthPicker
      {...args}
      value={value6}
      label="MMM YYYY"
      name="MMM YYYY"
      displayFormat="MMM YYYY"
      onChange={(e) => {
        setValue6(e.target.value);
        args.onChange?.(e);
      }}
    />
    <MonthPicker
      {...args}
      value={value6}
      label="MMM YYYY (en-US)"
      name="MMM YYYY (en-US)"
      displayFormat="MMM YYYY"
      locale="en-US"
      onChange={(e) => {
        setValue6(e.target.value);
        args.onChange?.(e);
      }}
    />
    <MonthPicker
      {...args}
      value={value6}
      label="MMM YYYY (ko-KR)"
      name="MMM YYYY (ko-KR)"
      displayFormat="MMM YYYY"
      locale="ko-KR"
      onChange={(e) => {
        setValue6(e.target.value);
        args.onChange?.(e);
      }}
    />
  </Stack>
```

### With Reset Button

A controlled example with an external reset button to clear the selected value.

```tsx
<div
    style={{
      display: "flex",
      gap: "10px"
    }}
  >
    <MonthPicker
      {...props}
      value={value}
      onChange={(event) => {
        setValue(event.target.value);
      }}
    />
    <Button onClick={() => setValue("")}>Reset</Button>
  </div>
```

## Billing Period Selection

```tsx
function BillingPeriodSelector() {
  const [billingMonth, setBillingMonth] = useState('');

  return (
    <MonthPicker
      label="Billing Period"
      value={billingMonth}
      onChange={(e) => setBillingMonth(e.target.value)}
      disableFuture
      helperText="Select the month for invoice generation"
    />
  );
}
```

## Report Month Filter with Display Format

```tsx
function ReportFilter() {
  const [reportMonth, setReportMonth] = useState('');

  return (
    <MonthPicker
      label="Report Month"
      value={reportMonth}
      onChange={(e) => setReportMonth(e.target.value)}
      disableFuture
      displayFormat="MMMM YYYY"
    />
  );
}
```

## Credit Card Expiry

```tsx
function CreditCardExpiry() {
  const [expiry, setExpiry] = useState('');

  const today = new Date();
  const minDate = `${today.getFullYear()}/${String(today.getMonth() + 1).padStart(2, '0')}/01`;

  return (
    <MonthPicker
      label="Card Expiry"
      value={expiry}
      onChange={(e) => setExpiry(e.target.value)}
      minDate={minDate}
      displayFormat="MM/YYYY"
      helperText="Enter card expiration date"
      required
    />
  );
}
```

## Best Practices

1. **Match value format to `format` prop**: The `value` prop must follow the same pattern as `format`. Mismatches cause unexpected behavior.

```tsx
// ✅ Good: Value matches default format
<MonthPicker value="2024/04/01" />

// ❌ Bad: Value missing the day component
<MonthPicker value="2024/04" />
```

2. **Use `displayFormat` for user-friendly presentation**: Keep the value format stable for programmatic use, and customize only the visible representation.

```tsx
// ✅ Good: Separate concerns
<MonthPicker format="YYYY/MM/DD" displayFormat="MMMM YYYY" />
```

3. **Provide context with `helperText`**: Guide users on what they are selecting, especially when constraints are applied.

```tsx
// ✅ Good: Clear guidance
<MonthPicker label="Statement Month" helperText="Select the month for your account statement" disableFuture />
```

4. **Set reasonable date constraints**: Use `minDate`, `maxDate`, `disableFuture`, or `disablePast` to prevent invalid selections at the UI level.

```tsx
// ✅ Good: Logical constraints
<MonthPicker disableFuture minDate="2020/01/01" />
```

5. **Handle the day component in values**: Remember that `onChange` values always include a day set to `01`. Extract year and month when only those parts are needed.

```tsx
// ✅ Good: Extract month/year
const handleChange = (e) => {
  const [year, month] = e.target.value.split('/');
  setSelectedPeriod({ year: parseInt(year), month: parseInt(month) });
};
```

## Props and Customization

### Key Props

| Prop            | Type                                                    | Default        | Description                                                                                                |
| --------------- | ------------------------------------------------------- | -------------- | ---------------------------------------------------------------------------------------------------------- |
| `value`         | `string \| null`                                        | -              | Selected month string in `format` (controlled mode)                                                        |
| `defaultValue`  | `string`                                                | -              | Initial month string (uncontrolled mode)                                                                   |
| `onChange`      | `(event: { target: { name?, value: string } }) => void` | -              | Callback when the month changes                                                                            |
| `format`        | `string`                                                | `'YYYY/MM/DD'` | Format of the `value` and `onChange` value                                                                 |
| `displayFormat` | `string`                                                | `'YYYY/MM'`    | Format displayed in the input field. Supports `MMM` (short month name) and `MMMM` (full month name) tokens |
| `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 entire component                                                                              |
| `inputReadOnly` | `boolean`                                               | `false`        | Prevents typing; clicking the input or calendar button toggles the calendar for selection                  |
| `readOnly`      | `boolean`                                               | `false`        | Prevents typing and opening the calendar, including when `inputReadOnly` is enabled                        |
| `name`          | `string`                                                | -              | HTML name attribute for form submission                                                                    |
| `minDate`       | `string`                                                | -              | Minimum selectable month (in `format`)                                                                     |
| `maxDate`       | `string`                                                | -              | Maximum selectable month (in `format`)                                                                     |
| `disableFuture` | `boolean`                                               | `false`        | Disables all future months                                                                                 |
| `disablePast`   | `boolean`                                               | `false`        | Disables all past months                                                                                   |
| `locale`        | `string`                                                | `'default'`    | Locale for month names (BCP 47 format)                                                                     |

> **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.

### Alphabetic Month Tokens (MMM / MMMM)

The `displayFormat` prop supports alphabetic month tokens for more human-readable month display:

| Token  | Output                 | Example                        |
| ------ | ---------------------- | ------------------------------ |
| `MMM`  | Abbreviated month name | `Jan`, `Feb`, `Apr`            |
| `MMMM` | Full month name        | `January`, `February`, `April` |

Use the `locale` prop to control the language of month names.

```tsx
<MonthPicker displayFormat="MMM YYYY" locale="en-US" />
// → "Apr 2026"

<MonthPicker displayFormat="MMMM YYYY" locale="ko-KR" />
// → "4월 2026"
```

> **Note**: MonthPicker also accepts all Input props (e.g., `size`, `variant`, `color`, `sx`).

## Accessibility

- With `inputReadOnly`, the input uses the native `readOnly` attribute to prevent typing and avoid opening a virtual keyboard on touch devices. The calendar button remains available for keyboard selection.
- The input has `role="textbox"` and the calendar toggle button has `aria-label="Toggle Calendar"` for screen reader identification.
- **Keyboard navigation**: Use **Tab** to move focus between the input and calendar button, **Enter/Space** to open the calendar, **Arrow Keys** to navigate months, and **Escape** to close the popup.
- Each month button in the calendar grid has a descriptive `aria-label` (e.g., "April 2024") so screen readers announce the full context.
- Focus management moves focus into the calendar grid when opened and returns focus to the input when the calendar is closed.
