import {useState, useEffect} from 'react'
import React from 'react'

import axios from 'axios';


import PropTypes from 'prop-types';

//import { useNavigate, useLocation } from 'react-router-dom';
import { Button } from '@mui/material'

import AddIcon from '@mui/icons-material/Add';
import DeleteIcon from '@mui/icons-material/DeleteOutlined';

import { DataGrid, GridToolbarContainer, GridActionsCellItem } from '@mui/x-data-grid';
import Snackbar from '@mui/material/Snackbar';
import Alert from '@mui/material/Alert';

const baseURL = "http://localhost:8000/api"
const apiURL = "/article/packaging/"


  
function EditToolbar(props) {
    const { setTableData, articleId } = props;

    const handleClick = async () => {

        const newValue = { packaging_id: {id: -1, name: 'Bitte auswählen'}, weight: 0, isNew: true, article_id: articleId };
        const receivedData = await axios.post(baseURL+"/article/articlePackagings/"+articleId, {
            newValue, 
        })

        //console.log(receivedData)    
        const newRow = { id: receivedData.data.id, packaging_id: {id: -1, name: 'Bitte auswählen'}, weight: receivedData.data.weight, isNew: true, article_id: receivedData.data.article_id };

        setTableData((oldRows) => [...oldRows, newRow]);
    };

    return (
        <GridToolbarContainer>
        <Button color="primary" startIcon={<AddIcon />} onClick={handleClick}>
            Neuer Eintrag
        </Button>
        </GridToolbarContainer>
    );
}

EditToolbar.propTypes = {
    setTableData: PropTypes.func.isRequired,
}

const PackagingDataGrid2 = (props) => {
    const { articleId } = props;
    
    const [list, setList] = useState([]);
    const [tableData, setTableData] = useState([{id: -1, packaging_id: {id: -1, name: ''}, weight: -1, article_id: -1}]);
    const [snackbar, setSnackbar] = useState(null);

    const columnsPackaging = [
        {
            field: 'packaging_id', 
            headerName: 'Material',
            flex: 1,
            type: 'singleSelect',
            valueOptions: () => {return list.map(x => x.name).sort()},
            editable: true,
            valueGetter: (params) => {try {return params.row.packaging_id.name;} catch {return '';} },
        },
        {
            field: 'weight', 
            headerName: 'Gewicht in g', 
            type: 'number',
            width:100,
            editable: true,
        },
        {
            field: 'actions',
            type: 'actions',
            headerName: 'Aktionen',
            width: 100,
            cellClassName: 'actions',
            getActions: ({ id }) => {    
              return [
                <GridActionsCellItem
                  icon={<DeleteIcon />}
                  label="Delete"
                  onClick={(e) => handleDeleteClick(id,e)}
                  color="inherit"
                />,
              ];
            },
        }
    ]

    const findId = (idToLookFor) => {
        for (var i = 0; i < list.length; i++) {
            if (list[i].name === idToLookFor) {
                return(list[i].id);
            }
        }
    }

    const handleCloseSnackbar = () => setSnackbar(null);

    //Anscheinend ist es notwendig das event e zu übergeben, ansonsten passieren komische Dinge (kein async, multiple trigger beim rendern etc)
    const handleDeleteClick = async (id,e) => {
        const newData = tableData.filter((row) => row.id !== id);
        //console.log('Delete clicked')
        //console.log(id)
        //console.log(e)
        try {
            const receivedData = await axios.delete(baseURL+"/article/articlePackagings/"+articleId, {
                data: id, 
            })
            setSnackbar({ children: 'Änderungen erfolgreich gespeichert', severity: 'success' });
            setTableData(newData);
        } catch (error) {
            setSnackbar({ children: error.message, severity: 'error' });
        }
      };
    
    const processRowUpdate = React.useCallback( async (newRow, oldRow) => {
        const id = findId(newRow.packaging_id);
        const updatedRow = {'id': newRow.id, 'packaging_id':{'id': id, 'name': newRow.packaging_id}, 'weight': newRow.weight, 'isNew': false, 'article_id': articleId};
        const newData = tableData.map((row) => (row.id === newRow.id ? updatedRow : row));

        try {
            const response = await axios.put(baseURL+"/article/articlePackagings/"+articleId, {
                updatedRow 
            });

            //console.log(response);
            setSnackbar({ children: 'Änderungen erfolgreich gespeichert', severity: 'success' });

            setTableData(newData);
            //onChange(newData);
            return updatedRow;
        } catch (error) {
            setSnackbar({ children: error.message, severity: 'error' });
            return oldRow;
 
        }
      }
    );

    //const handleProcessRowUpdateError = React.useCallback((error) => {
    //    setSnackbar({ children: error.message, severity: 'error' });
    //}, []);


    useEffect(()=>{      
        axios.get(baseURL+apiURL)
             .then((res) => {
                const data = res.data;
                setList(data);
            })

        axios.get(baseURL+"/article/articlePackagings/"+articleId)
            .then((res) => {
                const data = res.data;
                //Add id for each element for displaying in Data Grid
                //data.forEach((item, i) => {
                //    item.id = i + 1;
                //});

                setTableData(data);
                //console.log("Fetching packaging data")
                //console.log(data)
            })

    },[])
    
    return (
        <div style={{ height: 350, width: '100%' }}>
            <DataGrid 
                rows={tableData}
                columns={columnsPackaging}
                pageSize={10}
                editMode="row"
                //getRowId={(row) => row.internalId}
                processRowUpdate={processRowUpdate}
                //onProcessRowUpdateError={handleProcessRowUpdateError}
                experimentalFeatures={{ newEditingApi: true }}
                components={{
                    Toolbar: EditToolbar,
                }}
                componentsProps={{
                    toolbar: { setTableData, articleId },
                }}

            />
            {!!snackbar && (
                <Snackbar
                open
                anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
                onClose={handleCloseSnackbar}
                autoHideDuration={6000}
                >
                <Alert {...snackbar} onClose={handleCloseSnackbar} />
                </Snackbar>
            )}
        </div>
    );
}

export default PackagingDataGrid2
