import Button from '@material-ui/core/Button';
import { useCallback, useContext, useEffect, useState } from 'react';
import { useHistory } from 'react-router';
import List from '../components/List/List';
import PageTitle from '../components/PageTitle/PageTitle';
import AuthContext from '../contexts/AuthContext';
import * as api from "./../api/api";



const Jobs = () => {
  const authCtx = useContext(AuthContext);
  const [jobs, setjobs] = useState([]);
  const [listSelection, setlistSelection] = useState([]);

  const fetchJobsHandler = useCallback(async () => {
    api
      .getAllJobs(authCtx.accessToken)
      .then((data) => {
        if (authCtx.role === "employee") {
          console.log(data)
          data.forEach((d) => {
            d.customerNames= ""
            d.participants.forEach(u => {
              d.customerNames += `${u.profile.firstname} ${u.profile.lastname} (${u.profileId}); `
            })
            if(d.advisor){
              d.advisorName = `${d.advisor.firstname} ${d.advisor.lastname} (${d.advisorId})`
            } 
          })

          setjobs(data);
        }
        if (authCtx.role === "customer") {
          data.projects.forEach((d) => {
            d.advisorName = d.advisorId
          })

          setjobs(data.projects);
        }
      })
  }, [authCtx.accessToken, authCtx.role]);

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

  const history = useHistory();
  const editHistory = (data) => history.push(data.pathTo);

  const columns = [
    { field: "id", headerName: "ID", width: 70 },
    { field: "name", headerName: "Name", width: 250 },
    { field: "description", headerName: "Description", width: 130 },
    { field: "price", headerName: "Price", width: 130 },
    { field: "advisorName", headerName: "Advisor", width: 130 },
    { field: "customerNames", headerName: "Customer(s)", width: 200 },
  ];

  const addJobHandler = () => {
    editHistory({ pathTo: "/jobs/new" });
  };

  const editJobHandler = () => {
    if (listSelection.length !== 1) {
      return;
    }

    const editId = listSelection[0];
    editHistory({ pathTo: `/jobs/detail/${editId}` });
  };

  const deleteJobHandler = () => {
    if (listSelection.length !== 1) {
      alert("Please select exactely 1 item to delete.");
      return;
    }

    api.deleteJob(authCtx.accessToken, {}, listSelection[0]).then(() => {
      alert("Job successfully deleted.");
      fetchJobsHandler();
    });
  };
  
    return (
        <div>
          <PageTitle titleText="Jobs" />
            <div>
            {authCtx.role === "employee" && <>
            <Button onClick={addJobHandler} variant="outlined">Create Job</Button>
            <Button onClick={editJobHandler} variant="outlined">Edit Job</Button>
            <Button onClick={deleteJobHandler} variant="outlined">Delete Job</Button>  
            </>
          }
            <Button onClick={fetchJobsHandler} variant="outlined">Refresh</Button>  
                <List onEntrySelect={(data) => setlistSelection(data)} isLoading={false} rows={jobs} columns={columns}/>
  
            </div>

        </div>
    )
}

export default Jobs