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 EditEmployee = () => {
  const authCtx = useContext(AuthContext)
  const [returnContent, setreturnContent] = useState("")

  const { id } = useParams()

  const [isLoading, setisLoading] = useState(true)

  const titleText = "Update Employee"
  const submitButtonText = "Update Employee"

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

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

        const fieldsTmp = [
          {key: 1, name: "firstname", label: "Firstname", type: "text",     required: true, value: data.employee.firstname},
          {key: 2, name: "lastname",  label: "Lastname",  type: "text",     required: true, value: data.employee.lastname },
          {key: 3, name: "mail",      label: "email",     type: "email",    required: true, value: data.employee.mail },
        ]
        setfields(fieldsTmp)
        
      })
      .finally(() => setisLoading(false));
  }, [authCtx.accessToken, id]);

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


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


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

export default EditEmployee;
