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 Employees = () => {
  const authCtx = useContext(AuthContext);
  const [employees, setemployees] = useState([]);
  const [listSelection, setlistSelection] = useState([]);
  const fetchEmployeesHandler = useCallback(async () => {
    api
      .getAllEmployees(authCtx.accessToken)
      .then((data) => {
        setemployees(data.employees);
      })
      .catch((e) => {
      });
  }, [authCtx.accessToken]);

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

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

  const columns = [
    { field: "id", headerName: "ID", width: 70 },
    { field: "firstname", headerName: "Firstname", width: 250 },
    { field: "lastname", headerName: "Lastname", width: 130 },
    { field: "mail", headerName: "Email", width: 200 },
  ];

  const addEmployeeHandler = () => {
    editHistory({ pathTo: "/employees/new" });
  };

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

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

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

    api.deleteEmployee(authCtx.accessToken, {}, listSelection[0]).then((d) => {
      alert(d.success);
      fetchEmployeesHandler();
    });
  };
  
    return (
        <div>
          <PageTitle titleText="Employees" />
            <div>
  
            <Button onClick={addEmployeeHandler} variant="outlined">Create Employee</Button>
            <Button onClick={editEmployeeHandler} variant="outlined">Edit Employee</Button>
            <Button onClick={deleteEmployeeHandler} variant="outlined">Delete Employee</Button>  
            <Button onClick={fetchEmployeesHandler} variant="outlined">Refresh</Button>  
                <List onEntrySelect={(data) => setlistSelection(data)} isLoading={false} rows={employees} columns={columns}/>
  
            </div>

        </div>
    )
}

export default Employees