import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import { parseISO, format, isValid } from "date-fns";

/**
 * Month input over MUI X DatePicker (year + month views only). String in /
 * string out ("yyyy-MM", or ""), matching the legacy AdminDatePicker mode="month"
 * so it drops into existing form/filter state. cs locale is provided by the
 * LocalizationProvider in MuiProvider.
 */
export default function MonthField({
  value,
  onChange,
  label,
  disabled,
  minDate,
  maxDate,
}: {
  value: string;
  onChange: (value: string) => void;
  label?: string;
  disabled?: boolean;
  minDate?: Date;
  maxDate?: Date;
}) {
  const parsed = value ? parseISO(`${value}-01`) : null;
  return (
    <DatePicker
      label={label}
      disabled={disabled}
      minDate={minDate}
      maxDate={maxDate}
      views={["year", "month"]}
      openTo="month"
      value={parsed && isValid(parsed) ? parsed : null}
      onChange={(d) => onChange(d && isValid(d) ? format(d, "yyyy-MM") : "")}
      format="MM.yyyy"
      slotProps={{ textField: { size: "small", fullWidth: true } }}
    />
  );
}
