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

// Fixed reference date — only the time part matters for parse/format round-trips.
const REF = new Date(2000, 0, 1);

/**
 * Time input over MUI X TimePicker. String in / string out ("HH:mm", or ""),
 * 24-hour, configurable minute step (default 5) — matches the legacy
 * AdminDatePicker mode="time". cs locale comes from MuiProvider's
 * LocalizationProvider.
 */
export default function TimeField({
  value,
  onChange,
  label,
  disabled,
  minutesStep = 5,
}: {
  value: string;
  onChange: (value: string) => void;
  label?: string;
  disabled?: boolean;
  minutesStep?: number;
}) {
  const parsed = value ? parse(value, "HH:mm", REF) : null;
  return (
    <TimePicker
      label={label}
      disabled={disabled}
      ampm={false}
      minutesStep={minutesStep}
      value={parsed && isValid(parsed) ? parsed : null}
      onChange={(d) => onChange(d && isValid(d) ? format(d, "HH:mm") : "")}
      slotProps={{ textField: { size: "small", fullWidth: true } }}
    />
  );
}
