import { useState, useContext, useCallback, useEffect } from "react";
import * as api from "./../api/api";
import AuthContext from "./../contexts/AuthContext"
import CrudForm from "../components/CrudForm/CrudForm";
import { useParams } from "react-router";
import PageTitle from "../components/PageTitle/PageTitle";
import { CircularProgress } from "@material-ui/core";

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

  const { id } = useParams()

  const [isLoading, setisLoading] = useState(true)

  const titleText = "Update Job"
  const submitButtonText = "Update Job"

  const [fields, setfields] = useState([])

  const fetchJob = useCallback(async () => {
    setisLoading(true)
    api
      .getSpecificJob(authCtx.accessToken, id)
      .then((data) => {

        const fieldsTmp = [
          {key: 1, name: "name", label: "Name", type: "text",     required: true, value: data.project.name},
          {key: 2, name: "description",  label: "Description",  type: "text",     required: false, value: data.project.description },
          {key: 3, name: "price",      label: "Price",     type: "email",    required: true, value: data.project.price },
          {key: 4, name: "advisorId",  label: "AdvisorId",  type: "password", required: true, value: data.project.advisorId }
        ]
        setfields(fieldsTmp)
        
      })
      .finally(() => setisLoading(false));
  }, [authCtx.accessToken, id]);

  useEffect(() => {
    fetchJob();
  }, [fetchJob]);


  const submitHandler = (usr) => {
    api
      .updateJob(authCtx.accessToken, usr, id)
      .then(() => {
        setreturnContent(`Success.`)
      })
      .catch(() => {
        setreturnContent("An error occured... Please try again.")
      })
    
  };


  return (
    <div>
      <PageTitle titleText={`Edit Job with ID ${id}`} />
      {isLoading && <CircularProgress />}
      {!isLoading && <CrudForm
        submitHandler={submitHandler}
        titleText={titleText}
        submitButtonText={submitButtonText}
        fields={fields}
        returnContent={returnContent}
      />}
      
    </div>
  );
};

export default EditJob;
