import { useState, useContext } from "react";
import * as api from "./../api/api";
import AuthContext from "./../contexts/AuthContext"
import CrudForm from "../components/CrudForm/CrudForm";

const NewJob = () => {
  const authCtx = useContext(AuthContext)
  const [returnContent, setreturnContent] = useState("")

  const addJobHandler = (usr) => {
    if (usr.advisorId === ""){
      delete usr.advisorId
    }

    api
      .newJob(authCtx.accessToken, usr)
      .then((data) => {
        setreturnContent(`Success. ${data.success}`)
      })
      .catch((e) => {
        setreturnContent("An error occured... Please try again.")
      })
  };

  const titleText = "Create a new Job"
  const submitButtonText = "Add Job"

  const fields = [
    {key: 1, name: "name", label: "Name", type: "text",     required: true },
    {key: 2, name: "description",  label: "Description",  type: "text",     required: false },
    {key: 3, name: "price",      label: "Price",     type: "number",    required: false },
    {key: 4, name: "advisorId",  label: "Advisor ID",  type: "number", required: false },
    {key: 5, name: "customerId",  label: "Customer ID",  type: "number", required: true },
  ]



  return (
    <CrudForm
      submitHandler={addJobHandler}
      titleText={titleText}
      submitButtonText={submitButtonText}
      fields={fields}
      returnContent={returnContent}
    />
  );
};

export default NewJob;
