import React from "react";
import { Box, TextField, FormHelperText, FormControl } from "@mui/material";
import PropTypes from "prop-types";

function DateRangeInput({ field, disabled, onChange, error, helperText }) {
 let value = { from: "", to: "" };
try {
  value = field.ProValue ? JSON.parse(field.ProValue) : { from: "", to: "" };
} catch (e) {
  throw new Error(`Invalid date_range JSON for ${field.Label}: ${e.message}`);
}

  const handleChange = (key, val) => {
    const updated = { ...value, [key]: val };
    onChange(JSON.stringify(updated));
  };

  return (
    <FormControl fullWidth disabled={disabled} error={error}>
      <Box display="flex" gap={2} id={`field-${field.Id}`}>
        <TextField
          type="datetime-local"
          label={`${field.Label} From`}
          value={value.from || ""}
          disabled={disabled}
          onChange={(e) => handleChange("from", e.target.value)}
          InputLabelProps={{ shrink: true }}
          fullWidth
        />
        <TextField
          type="datetime-local"
          label={`${field.Label} To`}
          value={value.to || ""}
          disabled={disabled}
          onChange={(e) => handleChange("to", e.target.value)}
          InputLabelProps={{ shrink: true }}
          fullWidth
        />
      </Box>
      <FormHelperText className="helper-custom" error={error}>{helperText}</FormHelperText>
    </FormControl>

  );
}

export default DateRangeInput;

DateRangeInput.propTypes = {
  field: PropTypes.shape({
    Id: PropTypes.string.isRequired,
    Label: PropTypes.string.isRequired,
    ProValue: PropTypes.string,
  }).isRequired,
  disabled: PropTypes.bool,
  onChange: PropTypes.func.isRequired,
  error: PropTypes.bool,
  helperText: PropTypes.string,
};
