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 Customers = () => {
  const authCtx = useContext(AuthContext);
  const [customers, setcustomers] = useState([]);
  const [listSelection, setlistSelection] = useState([])
  
  const fetchCustomersHandler =  useCallback( async () => {

      api
        .getAllCustomers(authCtx.accessToken)
        .then((data) => {
          setcustomers(data.customers);
        })

  }, [authCtx.accessToken])

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

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

  const columns = [
      { field: 'id', headerName: 'ID', width: 70 },
      { field: 'company', headerName: 'Company', width: 130 },
      { field: 'firstname', headerName: 'Firstname', width: 250 },
      { field: 'lastname', headerName: 'Lastname', width: 130 },
      { field: 'mail', headerName: 'Email', width: 130 },
      { field: 'phoneNumber', headerName: 'Phone Number', width: 130 },
      { field: 'street', headerName: 'Street', width: 130 },
      { field: 'city', headerName: 'City', width: 130 },
      { field: 'zip', headerName: 'PLZ', width: 130 },
      { field: 'country', headerName: 'Country', width: 130 }
  ];



  const addCustomerHandler = () => {
    editHistory({pathTo: '/customers/new'})
  }
  
  const editCustomerHandler = () => {
    if (listSelection.length !== 1 ){
      alert("Please select exactely 1 item to edit.")
      return
    }

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

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

    api.deleteCustomer(authCtx.accessToken, {}, listSelection[0]).then((d) => {
      alert(d.success);
      fetchCustomersHandler();
    });
    
  };
  
    return (
        <div>
          <PageTitle titleText="Customers" />
            <div>
  
            <Button onClick={addCustomerHandler} variant="outlined">Create Customer</Button>
            <Button onClick={editCustomerHandler} variant="outlined">Edit Customer</Button>
            <Button onClick={deleteCustomerHandler} variant="outlined">Delete Customer</Button>  
            <Button onClick={fetchCustomersHandler} variant="outlined">Refresh</Button>  
                <List onEntrySelect={(data) => setlistSelection(data)} isLoading={false} rows={customers} columns={columns}/>
  
            </div>

        </div>
    )
}

export default Customers;