import TextField from "@material-ui/core/TextField";
import { Button } from "@material-ui/core";
import { useRef } from "react";

const CrudForm = (props) => {
  const myRefs = useRef([]);
  const submitHandler = (e) => {
    e.preventDefault();
    const usrObj = {};

    myRefs.current.forEach((element) => {
      usrObj[element.name] = element.value;
    });
    props.submitHandler(usrObj);
  };

  return (
    <>
      <div>
        <h2>{props.titleText}</h2>
        <form onSubmit={submitHandler} autoComplete="off">
          {props.fields.map((field) => {
            return (
              <div key={field.key}>
                <TextField
                  defaultValue={field.value}
                  name={field.name}
                  label={field.label}
                  inputRef={(el) => (myRefs.current[field.key] = el)}
                  required={field.required}
                />
                <br />
              </div>
            );
          })}

          <br />
          <Button color="primary" type="submit" variant="contained">
            {props.submitButtonText}
          </Button>
        </form>

        <p>{props.returnContent}</p>
      </div>
    </>
  );
};

export default CrudForm;
