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

  const { id } = useParams()

  const [isLoading, setisLoading] = useState(true)

  const props = {
    titleText: "Update customer",
    submitButtonText: "Update customer",
  };

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

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

        const fieldsTmp = [
          {key: 1, name: "company",     label: "Company",     type: "text",  required: false, value: data.customer.company },
          {key: 2, name: "firstname",   label: "Firstname",   type: "text",  required: true,  value: data.customer.firstname },
          {key: 3, name: "lastname",    label: "Lastname",    type: "text",  required: true,  value: data.customer.lastname },
          {key: 4, name: "street",      label: "street",      type: "text",  required: true,  value: data.customer.street },
          {key: 5, name: "mail",        label: "email",       type: "email", required: true,  value: data.customer.mail },
          {key: 6, name: "phoneNumber", label: "phoneNumber", type: "text",  required: false,  value: data.customer.phoneNumber },
          {key: 7, name: "city",        label: "city",        type: "text",  required: true,  value: data.customer.city },
          {key: 8, name: "zip",         label: "zip",         type: "number",  required: true,  value: data.customer.zip },
          {key: 9, name: "country",     label: "country",     type: "text",  required: true,  value: data.customer.country },
        ]
        setfields(fieldsTmp)
        
      })
      .finally(() => setisLoading(false));
  }, [authCtx.accessToken, id]);

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




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

 

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

export default EditCustomer;
