export default function EditarModal({ tipo, coord, show, close, setCoords }) {
  const handleSubmit = (e) => {
    e.preventDefault();

    const formData = new FormData(e.target);
    const x = formData.get("x");
    const y = formData.get("y");
    const z = formData.get("z");

    let storedTipo = localStorage.getItem(tipo);
    if (storedTipo) {
      let arr = JSON.parse(storedTipo);
      const index = arr.findIndex((item) => item.num === coord.num);
      if (index !== -1) {
        arr[index] = {
          ...coord,
          x: Number(x),
          y: y ? Number(y) : null,
          z: Number(z),
        };
        localStorage.setItem(tipo, JSON.stringify(arr));
        setCoords(arr);
      }
    }
    close();
  };

  if (!show) {
    return null;
  }

  return (
    <div
      className="modal"
      id="formModal"
      tabIndex="-1"
      style={{ display: "block" }}
    >
      <div className="modal-dialog">
        <div className="modal-content">
          <div className="modal-header">
            <h5 className="modal-title">Update Coord</h5>
            <button
              type="button"
              className="btn-close"
              onClick={close}
            ></button>
          </div>
          <div className="modal-body">
            <form onSubmit={handleSubmit}>
              <div className="mb-3">
                <label className="form-label">Coordenada X</label>
                <input
                  type="number"
                  name="x"
                  className="form-control"
                  defaultValue={coord.x}
                />
              </div>
              {coord.y != null && (
                <div className="mb-3">
                  <label className="form-label">Coordenada Y</label>
                  <input
                    type="number"
                    name="y"
                    className="form-control"
                    defaultValue={coord.y}
                  />
                </div>
              )}
              <div className="mb-3">
                <label className="form-label">Coordenada Z</label>
                <input
                  type="number"
                  name="z"
                  className="form-control"
                  defaultValue={coord.z}
                />
              </div>
              <hr />
              <button type="submit" className="btn btn-primary m-2">
                Actualizar
              </button>
              <button
                type="button"
                className="btn btn-secondary"
                onClick={close}
              >
                Cancelar
              </button>
            </form>
          </div>
        </div>
      </div>
    </div>
  );
}
