import { DateField } from "@mui/x-date-pickers";
import { dateToTime, timeToDate } from "../../utils/DateUtils";
import { TextFieldVariants } from "@mui/material";

export function DateInput(p: {
  ref?: React.Ref<HTMLInputElement>;
  editable?: boolean;
  autoFocus?: boolean;
  label?: string;
  style?: React.CSSProperties;
  value: number | undefined;
  onValueChange: (v: number | undefined) => void;
  variant?: TextFieldVariants;
}): React.ReactElement {
  return (
    <DateField
      autoFocus={p.autoFocus}
      readOnly={p.editable === false}
      label={p.label}
      slotProps={{
        textField: {
          ref: p.ref,
          variant: p.variant ?? "standard",
          style: p.style,
        },
      }}
      value={timeToDate(p.value)}
      onChange={(v) => {
        try {
          p.onValueChange(dateToTime(v ?? undefined));
        } catch (e) {
          console.warn("Failed to parse date!", e);
        }
      }}
    />
  );
}
