# MonthRangePicker

## Introduction

MonthRangePicker is a form input component that allows users to select a range of months (start month and end month) from a calendar popup. Unlike DateRangePicker which provides day-level granularity, MonthRangePicker focuses on month-level selection -- users click once to set the start month and again to set the end month.

It is ideal for scenarios like fiscal period reporting, quarterly comparisons, subscription durations, or any use case requiring a span of months without specific day selection. The component supports multiple value formats, controlled and uncontrolled modes, and date range constraints.

```tsx
<MonthRangePicker />
```

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

## Usage

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

function MonthRangeForm() {
  const [monthRange, setMonthRange] = useState('');

  return (
    <MonthRangePicker label="Select Month Range" value={monthRange} onChange={(e) => setMonthRange(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

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

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

## Form Field Features

### With Label

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

```tsx
<MonthRangePicker label="Month Range" />
```

### With Helper Text

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

```tsx
<MonthRangePicker
  label="Month"
  helperText="Please select a month"
/>
```

### Required Field

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

```tsx
<MonthRangePicker
  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
<MonthRangePicker
  label="Month"
  helperText="Please select a month"
  error
/>
```

### Disabled

Prevent user interaction when the picker is disabled.

```tsx
<MonthRangePicker disabled />
```

## Date Constraints

### Minimum Date

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

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

### Maximum Date

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

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

### Disable Future

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

```tsx
<MonthRangePicker disableFuture />
```

### Disable Past

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

```tsx
<MonthRangePicker disablePast />
```

## Controlled vs Uncontrolled

### Controlled

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

```tsx
<Stack gap={2}>
    <MonthRangePicker {...args} value={value} onChange={(e) => setValue(e.target.value)} />
    <Button
      onClick={() => {
        const [start, end] = value.split(" - ");
        function shiftMonth(dateString: string) {
          const currentValue = new Date(dateString);
          currentValue.setFullYear(currentValue.getFullYear() + 1);
          const year = currentValue.getFullYear();
          const month = String(currentValue.getMonth() + 1).padStart(2, "0");
          return `${year}/${month}`;
        }
        setValue(`${shiftMonth(start)} - ${shiftMonth(end)}`);
      }}
    >
      Shift Year
    </Button>
  </Stack>
```

### Uncontrolled

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

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

## Formats

The `format` prop determines both the display format and the value emitted by `onChange`. Unlike MonthPicker, MonthRangePicker does not have a separate `displayFormat` prop -- the `format` prop controls both.

The value is a string with start and end months separated by `-` (e.g., `"2024/04 - 2024/09"`).

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

### With Reset Button

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

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

## Fiscal Period Report

```tsx
function FiscalReportSelector() {
  const [period, setPeriod] = useState('');

  const handleGenerate = () => {
    if (!period) return;
    const [startMonth, endMonth] = period.split(' - ');
    generateReport({ startMonth, endMonth });
  };

  return (
    <Stack gap={2}>
      <MonthRangePicker
        label="Fiscal Period"
        value={period}
        onChange={(e) => setPeriod(e.target.value)}
        disableFuture
        helperText="Select the fiscal period for the report"
      />
      <Button onClick={handleGenerate} disabled={!period}>
        Generate Report
      </Button>
    </Stack>
  );
}
```

## Subscription Duration with Month Count

```tsx
function SubscriptionForm() {
  const [duration, setDuration] = useState('');

  const getMonthsCount = (value: string) => {
    if (!value) return 0;
    const [start, end] = value.split(' - ');
    const [startYear, startMonth] = start.split('/').map(Number);
    const [endYear, endMonth] = end.split('/').map(Number);
    return (endYear - startYear) * 12 + (endMonth - startMonth) + 1;
  };

  return (
    <MonthRangePicker
      label="Subscription Period"
      value={duration}
      onChange={(e) => setDuration(e.target.value)}
      disablePast
      helperText={
        getMonthsCount(duration) > 0 ? `${getMonthsCount(duration)} month subscription` : 'Select start and end months'
      }
      required
    />
  );
}
```

## Year-over-Year Comparison

```tsx
function YearOverYearComparison() {
  const [currentPeriod, setCurrentPeriod] = useState('');

  const getPreviousPeriod = (value: string) => {
    if (!value) return '';
    const [start, end] = value.split(' - ');
    const [sYear, sMonth] = start.split('/').map(Number);
    const [eYear, eMonth] = end.split('/').map(Number);
    return `${sYear - 1}/${String(sMonth).padStart(2, '0')} - ${eYear - 1}/${String(eMonth).padStart(2, '0')}`;
  };

  return (
    <Stack gap={2}>
      <MonthRangePicker
        label="Current Period"
        value={currentPeriod}
        onChange={(e) => setCurrentPeriod(e.target.value)}
        disableFuture
      />
      <MonthRangePicker label="Previous Period (Auto-calculated)" value={getPreviousPeriod(currentPeriod)} disabled />
    </Stack>
  );
}
```

## Best Practices

1. **Match value format to `format` prop**: The `value` prop must follow the same pattern as `format`, with start and end separated by `-`.

```tsx
// ✅ Good: Matching formats
<MonthRangePicker
  format="YYYY/MM"
  value="2024/04 - 2024/09"
/>

// ❌ Bad: Mismatched format
<MonthRangePicker
  format="YYYY/MM"
  value="04/2024 - 09/2024"
/>
```

2. **Show range duration in helper text**: Help users understand the length of the period they selected.

```tsx
// ✅ Good: Dynamic helper text
<MonthRangePicker helperText={`${getMonthsCount(range)} months selected`} />
```

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

```tsx
// ✅ Good: Logical constraints for historical reporting
<MonthRangePicker disableFuture minDate="2020/01" />
```

4. **Validate before processing**: Always check that the value is non-empty and properly formed before parsing.

```tsx
// ✅ Good: Guard against empty values
const handleSubmit = () => {
  if (!range || !range.includes(' - ')) return;
  const [start, end] = range.split(' - ');
  // process start and end
};
```

5. **Use consistent `format` across your application**: Choose one format (e.g., `YYYY-MM` for API compatibility) and stick with it.

```tsx
// ✅ Good: ISO format for API compatibility
<MonthRangePicker format="YYYY-MM" />
```

## Props and Customization

### Key Props

| Prop            | Type                                                    | Default          | Description                                                                                                          |
| --------------- | ------------------------------------------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------- |
| `value`         | `string \| null`                                        | -                | Selected month range string in `format` (controlled mode)                                                            |
| `defaultValue`  | `string`                                                | -                | Initial month range string (uncontrolled mode)                                                                       |
| `onChange`      | `(event: { target: { name?, value: string } }) => void` | -                | Callback when the month range changes                                                                                |
| `format`        | `string`                                                | `'YYYY/MM'`      | Format of the `value` and `onChange` value                                                                           |
| `displayFormat` | `string`                                                | same as `format` | Format displayed in the input field. Supports `MMM` (short month name) and `MMMM` (full month name) tokens           |
| `locale`        | `string`                                                | `'default'`      | Locale for month names when using `MMM`/`MMMM` tokens in `displayFormat` (BCP 47 format, e.g., `'en-US'`, `'ko-KR'`) |
| `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                                                                                        |
| `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                                                                                             |

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

When `displayFormat` contains `MMM` or `MMMM`, the input becomes **read-only** and the user must select months through the calendar popup. Use the `locale` prop to control the language of month names.

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

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

## Accessibility

- 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.
- Range selection is conveyed through visual highlighting between the start and end months in the calendar grid. Each month button has a descriptive `aria-label` (e.g., "April 2024").
- Focus management moves focus into the calendar grid when opened and returns focus to the input when the calendar is closed.
