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

/**
 * Date input over MUI X DatePicker. String in / string out ("yyyy-MM-dd", or ""),
 * so it drops into existing form state. cs locale + dd.MM.yyyy display are provided
 * by the LocalizationProvider in MuiProvider.
 */
export default function DateField({
  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) : null;
  return (
    <DatePicker
      label={label}
      disabled={disabled}
      minDate={minDate}
      maxDate={maxDate}
      value={parsed && isValid(parsed) ? parsed : null}
      onChange={(d) => onChange(d && isValid(d) ? format(d, "yyyy-MM-dd") : "")}
      format="dd.MM.yyyy"
      slotProps={{ textField: { size: "small", fullWidth: true } }}
    />
  );
}
