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

import axios from 'axios';

import dayjs from 'dayjs';

import { useNavigate, useLocation } from 'react-router-dom';

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

import PropTypes from 'prop-types';

import Grid from '@mui/material/Grid'
import Button from '@mui/material/Button'
import TextField from '@mui/material/TextField';
import Snackbar from '@mui/material/Snackbar';
import Alert from '@mui/material/Alert';
import Box from '@mui/material/Box';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogActions from '@mui/material/DialogActions';
import Select from '@mui/material/Select';
import MenuItem from '@mui/material/MenuItem';
import Checkbox from '@mui/material/Checkbox';
import InputAdornment from '@mui/material/InputAdornment';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormControl from '@mui/material/FormControl';
import InputLabel from '@mui/material/InputLabel';
import {Autocomplete, createFilterOptions} from '@mui/material'

import { grey } from '@mui/material/colors';

import AddIcon from '@mui/icons-material/Add';
import DeleteIcon from '@mui/icons-material/DeleteOutlined';
import EditIcon from '@mui/icons-material/Edit';
import SaveIcon from '@mui/icons-material/Save';

import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';

import MarketDetail from "./MarketDetail.component";
import ReceipeCanvas from "./Canvas.component"
import ListFieldApiwoArticle from "./ListFieldApiwoArticle.component"

const baseURL = "http://localhost:8000/api"

const filter = createFilterOptions();

function EditToolbar(props) {
    const { setArticles, setOpenNewEntryDialog } = props;

    const handleClick = async () => {
        console.log("Neuer Eintrag")
        setOpenNewEntryDialog(true);
        const retArticles = await axios.get(baseURL+"/articles/", {
           
        });

        // Here we just add a "Neuer Artikel" object to the list of all available articles. If this is selected later on, we ask the backend for a real new object.
        const answerWithNewArticelOption = retArticles.data.concat({pk:-1, name: 'Neuer Artikel', brand: null});
        setArticles(answerWithNewArticelOption);

    };

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

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

const PurchaseDetails = (props) => {
    const location = useLocation();
    //location.state != null ? console.log(location.state.id) : console.log("No data to show");
    
    const navigate = useNavigate();
    
    const noButtonRef = React.useRef(null);
    const drawRef = React.useRef({});

    const [img, setImg] = useState(new Image());
    const [tableData, setTableData] = useState([{id: 1, quantity: 0, article_id: {name: '', brand: {name: ''}}, price: 0, MwSt: 7, inSale: false, map: '', purchase_id: -1}]);
    const [drawData, setDrawData] = useState([]);
    const [snackbar, setSnackbar] = useState(null);
    const [rowModesModel, setRowModesModel] = useState({});
    const [purchaseArticleRowId, setPurchaseArticleRowId] = useState(null);
    const [doubleClickAllowed, setDoubleClickAllowed] = useState(true);
    const [promiseArguments, setPromiseArguments] = React.useState(null);
    const [openMapDialog, setOpenMapDialog] = useState(false);
    const [openExchangeDialog, setOpenExchangeDialog] = useState(false);
    const [openNewEntryDialog, setOpenNewEntryDialog] = useState(false);
    const [mapString, setMapString] = useState({receipeString: {id: -1, name: ""}, location_x: 0, location_y: 0, location_h: 0, location_w: 0, pk: -1, rowId: -1, purchase_id: -1, receipeString: ""});
    const [rowMode, setRowMod] = useState('view');
    const [stringData, setStringData] = useState([]);

    const [paymentType, setPaymentType] = useState(location.state.payment_type);
    const [totalPrice, setTotalPrice] = useState(location.state.total_price);
    const [purchaseDate, setpurchaseDate] = useState(location.state.purchase_date);

    const [newArticle,setNewArticle] = useState({id: 1, quantity: 0, article_id: {name: '', brand: {name: ''}}, price: 0, MwSt: 7, inSale: false, map: '', purchase_id: -1});
    const [articles, setArticles] = useState([]);
    const [exchangeArticle, setExchangeArticle] = useState({rowData: {}, newArticle: {}, deleteOld: false});
    //const [purchaseArticleRowId, setPurchaseArticleRowId, clearPurchaseArticleRowId] = useStickyState()

    const paymentTypes = ['','EC','Bar','Kreditkarte']

    const columns = [
        {
            field: 'quantity', 
            headerName: '#', 
            width: 60,
            type: 'number',
            editable: true,
        },
        {
            field: 'name', 
            headerName: 'Artikel',
            valueGetter: (params) => { const brandName = params.row.article_id.brand === null ? '' : params.row.article_id.brand.name; const articleName = params.row.article_id === null ? '' : params.row.article_id.name;
                                        return brandName + ' ' + articleName },
            width: 190,
            type: 'string',
        },
        {
            field: 'price', 
            headerName: 'Preis', 
            width: 80,
            type: 'number',
            editable: true,
            valueFormatter: (params) => {
                if (params.value == null) {
                  return '';
                }
  
                //const valueFormatted = Number(params.value * 100).toLocaleString();
                return `${params.value} €`;
              },
        },

        {
            field: 'MwSt', 
            headerName: 'MwSt', 
            valueGetter: (params) => { return params.row.article_id.MwSt },
            valueFormatter: (params) => {
                if (params.value == null) {
                  return '';
                }
  
                //const valueFormatted = Number(params.value * 100).toLocaleString();
                return `${params.value} %`;
              },
            width: 55,
            type: 'number',
            editable: true,
        },
        {
            field: 'inSale', 
            headerName: 'Sale',
            type: 'boolean',
            width: 55,
            editable: true,
        },
        {
            field: 'sum_price', 
            headerName: '∑ Preise',
            width: 80,
            type: 'number',
            valueFormatter: (params) => {
                if (params.value == null) {
                  return '';
                }
  
                //const valueFormatted = Number(params.value * 100).toLocaleString();
                return `${params.value.toFixed(2)} €`;
              },
        },
        {
            field: 'actions',
            type: 'actions',
            headerName: 'Aktionen',
            width: 100,
            cellClassName: 'actions',
            
            getActions: ({ id }) => {    
              return [
                <GridActionsCellItem
                    icon={(rowMode === 'edit' && purchaseArticleRowId === id) ? <SaveIcon /> : <EditIcon />}
                    label="Edit"
                    onClick={(e) => handleEditSaveClick(e,id)}
                    color="inherit"
                />,
                <GridActionsCellItem
                  icon={<DeleteIcon />}
                  label="Delete"
                  onClick={(e) => handleDeleteClick(id,e)}
                  color="inherit"
                />,
                <GridActionsCellItem
                    icon={<EditIcon />}
                    label="Kassenzettel-String bearbeiten"
                    onClick={(e) => handleEditMapClick(id,e)}
                    showInMenu
                />,
                <GridActionsCellItem
                    icon={<EditIcon />}
                    label="Artikel austauschen"
                    onClick={(e) => handleExchangeClick(id,e)}
                    showInMenu
                />,
                <GridActionsCellItem
                    icon={<EditIcon />}
                    label="Bereich übernehmen"
                    onClick={(e) => handleSaveLocation(id,e)}
                    showInMenu
            />,
              ];
            },

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

    const handleDataGridClick = (e) => {        
        if (purchaseArticleRowId !== e.row.id) {
            setRowModesModel({ ...rowModesModel, [purchaseArticleRowId]: { mode: GridRowModes.View } });
            setDoubleClickAllowed(true);
            setRowMod('view')
        } 
        
        setPurchaseArticleRowId( e.row.id );
        //setDrawData(e.row.map)

        drawRef.current.draw(e.row.map)
    }

   
    const handleDataGridDoubleClick = (e) => {
        console.log("PurchaseDetail->DoubleClick")
        console.log(e.row)
        if (doubleClickAllowed) {
            navigate('/ArticleDetails', {state:e.row});
        }
    }

    const handleEditSaveClick = (e, id) => {
        
        if (!purchaseArticleRowId) {
            return;
        }
        
        if (rowMode === 'edit') {
            setRowModesModel({ ...rowModesModel, [id]: { mode: GridRowModes.View } });
            setDoubleClickAllowed(true);
            setRowMod('view')
        } else {
            setRowModesModel({ ...rowModesModel, [id]: { mode: GridRowModes.Edit } });
            setDoubleClickAllowed(false);
            setRowMod('edit')
        }
        

        //console.log("Edit")
    };

    const processRowUpdate = React.useCallback( async (newRow, oldRow) => {
        const newArticle = { ...newRow.article_id, MwSt: newRow.MwSt };
        const updatedRow = {id: newRow.id, MSt: newRow.MwSt, article_id: newArticle, inSale: newRow.inSale, 
                            map: newRow.map, net_weight: newRow.net_weight, price: newRow.price, 
                            quantity: newRow.quantity, sum_price: newRow.quantity*newRow.price
                        };

        const newData = tableData.map((row) => (row.id === updatedRow.id ? updatedRow : row));

        try {
            const response = await axios.put(baseURL+"/purchase/article/"+newRow.id, {
                newRow: updatedRow 
            });

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

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

    const handleDeleteClick = async (id,e) => {
        console.log("Delete: "+id)
        
        /*
        try {
            const receivedData = await axios.delete(baseURL+"/purchase/article/"+id, {
                data: id, 
            })

            setSnackbar({ children: 'Änderungen erfolgreich gespeichert', severity: 'success' });
            setTableData(newData);
        } catch (error) {
            setSnackbar({ children: error.message, severity: 'error' });
        }*/
        new Promise((resolve, reject) => {
              setPromiseArguments({ resolve, reject, id });
              resolve(); // Nothing was changed

          })

      };

    const handleEditMapClick = (id, e) => {
        const currentRow = tableData.filter((row) => row.id === id)[0];
        setMapString({...currentRow.map,rowId: id});
        setOpenMapDialog(true);
    }

    const handleSaveLocation = async (id, e) => {
        var currentRow = tableData.filter((row) => row.id === id)[0];

        const locationData = {pk: currentRow.map.pk, 
                              receipeString: currentRow.map.receipeString, 
                              location_x: drawData.location_x,
                              location_y: drawData.location_y,
                              location_h: drawData.location_h,
                              location_w: drawData.location_w
                            };

        try {
            const receivedData = await axios.put(baseURL+"/article/maps/"+locationData.pk, {
                data: locationData, 
            })

            currentRow.map = locationData;
            const newData = tableData.map((row) => (row.id === currentRow.id ? currentRow : row));
            setTableData(newData);

            setSnackbar({ children: 'Änderungen erfolgreich gespeichert', severity: 'success' });
        } catch (error) {
            setSnackbar({ children: error.message, severity: 'error' });
 
        }

    }
    
    const handleMapClose = () => {
        setOpenMapDialog(false);
    }

    const handleExchangeClick = (id, e) => {
        const currentRow = tableData.filter((row) => row.id === id)[0];
        console.log(currentRow);
        setExchangeArticle({ ...exchangeArticle, oldRow: currentRow });
        setOpenExchangeDialog(true);
    }

    const handleExchangeClose = () => {
        setOpenExchangeDialog(false);
    }

    const handleNewEntryClose = async () => {
        setOpenNewEntryDialog(false);
    }

    const handleMapEdit = async () => {
        try {
            //const newMap = { ...mapString, receipeString: mapString };
            console.log(mapString)
            const receivedData = await axios.put(baseURL+"/article/maps/"+mapString.pk, {
                data: mapString, 
            })
            
            //const receivedData = null
            setSnackbar({ children: 'Änderungen erfolgreich gespeichert', severity: 'success' });

            var newRow = tableData.filter((row) => row.id === mapString.rowId)[0];
            newRow.map = mapString;
            const newData = tableData.map((row) => (row.id === mapString.rowId ? newRow : row));
            console.log(newData)
            setTableData(newData);

            setOpenMapDialog(false);
        } catch (error) {
            setSnackbar({ children: error.message, severity: 'error' });

        }
    }

    const handleArticleExchange = async () => {
        console.log(exchangeArticle)
        
        try {
            //const newMap = { ...mapString, receipeString: mapString };
            console.log(mapString)
            const receivedData = await axios.post(baseURL+"/exchangePurchaseArticles/", {
                data: exchangeArticle, 
            })
            
            const newData = tableData.map((row) => (row.id === exchangeArticle.oldRow.id ? receivedData.data : row));
            setTableData(newData);
            //const receivedData = null
            setSnackbar({ children: 'Änderungen erfolgreich gespeichert', severity: 'success' });


            setOpenExchangeDialog(false);
        } catch (error) {
            setSnackbar({ children: error.message, severity: 'error' });

        }
    }

    const handleNewEntryAdd = async () => {
        console.log(newArticle);
        if (newArticle.article_id.name === "Neuer Artikel") {
            try {
                const receivedData = await axios.post(baseURL+"/newPurchaseArticles/"+location.state.id+"/", {
                    data: newArticle,
                })
                console.log("Received new article:")
                console.log(receivedData.data)
                const newTableData = tableData.concat(receivedData.data);
                console.log(newTableData)
                setTableData(newTableData);
                updateTotalPrice(newTableData);
                setSnackbar({ children: 'Änderungen erfolgreich gespeichert', severity: 'success' });
                setOpenNewEntryDialog(false);

                setNewArticle({id: 1, quantity: 0, article_id: {name: '', brand: {name: ''}}, price: 0, MwSt: 7, inSale: false, map: '', purchase_id: -1})
            } catch (error) {
                setSnackbar({ children: error.message, severity: 'error' });
            }


        } else { 
            try {
                const sendData = {...newArticle, article_id: newArticle.article_id}
                const receivedData = await axios.post(baseURL+"/purchaseArticles/"+location.state.id+"/", {
                    data: sendData, 
                })

                //console.log(receivedData.data)
                const newTableData = tableData.concat(receivedData.data);
                console.log(receivedData.data)
                setTableData(newTableData);
                updateTotalPrice(newTableData);
                setSnackbar({ children: 'Änderungen erfolgreich gespeichert', severity: 'success' });
                setOpenNewEntryDialog(false);   

                setNewArticle({id: 1, quantity: 0, article_id: {name: '', brand: {name: ''}}, price: 0, MwSt: 7, inSale: false, map: '', purchase_id: -1})
            } catch (error) {
                setSnackbar({ children: error.message, severity: 'error' });
    
            }
           
        }
        
             
    }

    const handleNewArticleChange = (value) => {
        const selectedArticle = articles.filter((article) => article.pk === value.id )[0]
        setNewArticle({ ...newArticle, article_id: selectedArticle })
    }

    const handleSavePrice = async () => {
        console.log(location.state)
        const newPurchaseData = { ...location.state, total_price: totalPrice, payment_type: paymentType, purchase_date: purchaseDate, edit_finished: true, receipeImage: location.state.receipeImage.pk};

        try {
            
            const receivedData = await axios.put(baseURL+"/purchase/"+newPurchaseData.id, {
                data: newPurchaseData, 
            })
            
            setSnackbar({ children: 'Änderungen erfolgreich gespeichert', severity: 'success' });
            setPromiseArguments(null);
        } catch (error) {
            setSnackbar({ children: error.message, severity: 'error' });
            setPromiseArguments(null);
        }
    };

    const handleSaveDate = async (val) => {
        console.log(val.format("YYYY-MM-DD"))
        const newPurchaseData = { ...location.state, purchase_date: val.format("YYYY-MM-DD"), receipeImage: location.state.receipeImage.pk};

        try {
            
            const receivedData = await axios.put(baseURL+"/purchase/"+newPurchaseData.id, {
                data: newPurchaseData, 
            })
            
            setSnackbar({ children: 'Änderungen erfolgreich gespeichert', severity: 'success' });
            setPromiseArguments(null);
            setpurchaseDate(val.format("YYYY-MM-DD"));
        } catch (error) {
            setSnackbar({ children: error.message, severity: 'error' });
            setPromiseArguments(null);
        }
    };

    const handleNo = () => {
        const { resolve } = promiseArguments;
        resolve(); // Resolve with the old row to not update the internal state
        setPromiseArguments(null);
    };

    // If in delete dialog box yes is choosen, we will delete the article in the backend
    const handleYes = async () => {
        
        const { reject, resolve, id } = promiseArguments;

        try {
            
            const receivedData = await axios.delete(baseURL+"/purchase/article/"+id, {
                data: id, 
            })
            
            const newData = tableData.filter((row) => row.id !== id);
            setTableData(newData);
            updateTotalPrice(newData);
            setSnackbar({ children: 'Änderungen erfolgreich gespeichert', severity: 'success' });
            resolve(receivedData);
            setPromiseArguments(null);
        } catch (error) {
            setSnackbar({ children: error.message, severity: 'error' });
            reject();
            setPromiseArguments(null);
        }
        
    };



    const handleEntered = () => {
        // The `autoFocus` is not used because, if used, the same Enter that saves
        // the cell triggers "No". Instead, we manually focus the "No" button once
        // the dialog is fully open.
        // noButtonRef.current?.focus();
      };

    const renderExchangeDialog = () => {

        return (
            <Dialog open={openExchangeDialog} onClose={handleExchangeClose}>
                <DialogTitle>Austausch eines Artikels gegen einen vorhandenen Artikel</DialogTitle>
                <DialogContent>
                    <Grid container spacing={1}>
                        <Grid item xs={5} alignItems="stretch" style={{ display: "flex" }}>
                            Artikel austauschen gegen:
                        </Grid>
                        <Grid item xs={7} alignItems="stretch" style={{ display: "flex" }}>
                        {/*
                        <Select
                            fullWidth
                            id="exchangeArticle"
                            value={exchangeArticle.newArticle.name}
                            label="Artikel"
                            onChange={(e,t) => {setExchangeArticle({ ...exchangeArticle, newArticle: articles.filter((element) => element.pk === Number(t.key.replace('.$','')))[0] });}}
                        >
                            {articles.map((article) => (
                                <MenuItem
                                    key={article.pk}
                                    value={article.name}
                                    //style={getStyles(name, personName, theme)}
                                >
                                {(article.brand !== null ? article.brand.name : '')+' '+article.name}
                                </MenuItem>
                            ))}
                        </Select> */}
                        <Autocomplete
                            multiple={false}
                            id="exchangeArticle"
                            fullWidth
                            options={articles.map((article) => (
                                {name: article.name, brand: article.brand !== null ? article.brand.name : '', id: article.pk}
                                )).sort((a, b) => {
                                    const nameA = a.brand + ' ' +a.name.toUpperCase(); // ignore upper and lowercase
                                    const nameB = b.brand + ' ' +b.name.toUpperCase(); // ignore upper and lowercase
                                    if (nameA < nameB) {
                                    return -1;
                                    }
                                    if (nameA > nameB) {
                                    return 1;
                                    }
                                
                                    // names must be equal
                                    return 0;
                                })
                            }
                            groupBy={(option) => option.brand}
                            renderOption={(props, option) => (
                                <Box component="li" {...props} key={option.id}>
                                    {option.brand + ' ' +option.name}
                                </Box>
                                )}
                            getOptionLabel={(option) => {
                                if (option.name === undefined){
                                    return ""
                                }
                                else{
                                    return option.brand + ' ' +option.name
                                }
                            }}
                            renderInput={(params) => (
                                <TextField
                                    {...params}
                                    variant="standard"
                                    label='Marke + Artikel'
                                />
                            )}
                            //onChange={(event, newValue) => {handleNewArticleChange(newValue)}}
                            onChange={(e,t) => {setExchangeArticle({ ...exchangeArticle, newArticle: articles.filter((element) => element.pk === t.id)[0] });}}
                                            
                        />
                        </Grid>
                        <FormControlLabel control={
                            <Checkbox
                                label='Sale?'
                                checked={exchangeArticle.deleteOld}
                                onChange={(e) => {setExchangeArticle({ ...exchangeArticle, deleteOld: !exchangeArticle.deleteOld });}}
                                inputProps={{ 'aria-label': 'controlled' }}
                            />
                            } label="Ursprünglichen Artikel löschen?" 
                        />
                    </Grid>
                </DialogContent>
                <DialogActions>
                    <Button onClick={handleExchangeClose}>Abbrechen</Button>
                    <Button onClick={handleArticleExchange}>Änderung speichern</Button>
                </DialogActions>
            </Dialog>
        )
    }

    const renderConfirmDialog = () => {
        if (!promiseArguments) {
            return null;
        }

        //const { newRow, oldRow } = promiseArguments;

        return (
            <Dialog
                maxWidth="xs"
                TransitionProps={{ onEntered: handleEntered }}
                open={!!promiseArguments}
            >
            <DialogTitle>Sind sie sicher?</DialogTitle>
            <DialogContent dividers>
                {`Ein klick auf 'Ja' wir die Daten löschen.`}
            </DialogContent>
            <DialogActions>
                <Button ref={noButtonRef} onClick={handleNo}>
                Nein
                </Button>
                <Button onClick={handleYes}>Ja</Button>
            </DialogActions>
            </Dialog>
        );
    };

    const updateTotalPrice = (val) => {
        const sumWithInitial = val.reduce(
            (accumulator, currentValue) => accumulator + currentValue.sum_price,
            0
          );
        setTotalPrice(sumWithInitial.toFixed(2));
    };

    useEffect(()=>{      

        var myImage = new Image();
        myImage.src = baseURL+"/receipeImage/"+location.state.receipeImage.pk;
        setImg(myImage)
        drawRef.current.drawImage(myImage);

        axios.get(baseURL+"/purchaseArticles/"+location.state.id)
            .then((res) => {
                const data = res.data;
                //console.log(tableData)
                console.log(data)
                setTableData(data);

                updateTotalPrice(data);
            })

        axios.get(baseURL+"/articles/")
            .then((res) => {
                setArticles(res.data);
            })

        axios.get(baseURL+"/article/mapStrings/")
            .then((res) => {
                setStringData(res.data);
            })
            
    },[])
    

    
    return(
        <div style={{ height: 800, width: '100%' }}>
        <h1> Details zum Einkauf vom {purchaseDate} </h1>
        
        <LocalizationProvider dateAdapter={AdapterDayjs}>
            <DatePicker 
                value={dayjs(purchaseDate)} 
                onChange={handleSaveDate}
            />
        </LocalizationProvider>

        <Box sx={{ borderRadius: '4px', p: 2, border: '1px solid', borderColor: grey[300] }}>
            <MarketDetail 
                marketId={location.state.market.id} 
                purchaseId={location.state.id}
            />
        </Box>
        
        <Grid container spacing={1}>
                <Grid item xs={8}>
                    <div style={{ display: 'flex', height: '1200px' }}>
                        <div style={{ flexGrow: 1 }}>
                            {renderConfirmDialog()}
                            {renderExchangeDialog()}
                            {/*Map String Dialog*/}
                            <Dialog open={openMapDialog} onClose={handleMapClose}>
                                <DialogTitle>Bearbeiten des OCR-Artikel Strings</DialogTitle>
                                <DialogContent>
                                    <Grid container spacing={1}>
                                        {/*
                                        <TextField
                                            fullWidth
                                            margin="dense"
                                            id="mapStringField"
                                            //defaultValue={name != null ? name : ""}
                                            value={mapString.receipeString.receipeString}
                                            onChange={(e) => setMapString({ ...mapString, receipeString: {...mapString.receipeString, receipeString: e.target.value} })}
                                            error={(mapString.length === 0)}
                                            label="OCR Mapping String"
                                            type="text"
                                            variant="standard"
                                        />  
                                        */}
                                        <ListFieldApiwoArticle 
                                            apiURL="/article/mapStrings/" 
                                            titleName="String" 
                                            addName="String hinzufügen" 
                                            multiple={false}
                                            value={mapString.receipeString} 
                                            onChange={(e) => {setMapString({ ...mapString, receipeString: e })}}
                                            sx={{width:'400px'}}
                                            addNew={true}
                                        />
                                    </Grid>
                                </DialogContent>
                                <DialogActions>
                                <Button onClick={handleMapClose}>Abbrechen</Button>
                                <Button onClick={handleMapEdit}>Änderung speichern</Button>
                                </DialogActions>
                            </Dialog>
                            <Dialog open={openNewEntryDialog} onClose={handleNewEntryClose}>
                                <DialogTitle>Neuer Eintrag hinzufügen</DialogTitle>
                                <DialogContent>
                                    <Grid container spacing={1}>
                                        <Grid item xs={1}>
                                            <TextField
                                                fullWidth
                                                margin="dense"
                                                id="newQuantityField"
                                                //defaultValue={name != null ? name : ""}
                                                value={newArticle.quantity}
                                                onChange={(e) => setNewArticle({ ...newArticle, quantity: e.target.value })}
                                                error={(newArticle.quantity === 0)}
                                                label="#"
                                                type="number"
                                                variant="standard"
                                            />
                                        </Grid>
                                        <Grid item xs={5}>
                                            <Autocomplete
                                                multiple={false}
                                                id="tags-standard"
                                                fullWidth
                                                options={articles.map((article) => (
                                                    {name: article.name, brand: article.brand !== null ? article.brand.name : '', id: article.pk}
                                                    )).sort((a, b) => {
                                                        const nameA = a.brand + ' ' +a.name.toUpperCase(); // ignore upper and lowercase
                                                        const nameB = b.brand + ' ' +b.name.toUpperCase(); // ignore upper and lowercase
                                                        if (nameA < nameB) {
                                                        return -1;
                                                        }
                                                        if (nameA > nameB) {
                                                        return 1;
                                                        }
                                                    
                                                        // names must be equal
                                                        return 0;
                                                    })
                                                }
                                                groupBy={(option) => option.brand}
                                                renderOption={(props, option) => (
                                                    <Box component="li" {...props} key={option.id}>
                                                      {option.brand + ' ' +option.name}
                                                    </Box>
                                                  )}
                                                getOptionLabel={(option) => {
                                                    if (option.name === undefined){
                                                        return ""
                                                    }
                                                    else{
                                                        return option.brand + ' ' +option.name
                                                    }
                                                }}
                                                renderInput={(params) => (
                                                    <TextField
                                                        {...params}
                                                        variant="standard"
                                                        label='Marke + Artikel'
                                                    />
                                                )}
                                                onChange={(event, newValue) => {handleNewArticleChange(newValue)}}
                                                              
                                            />
                                        </Grid>
                                        <Grid item xs={2}>
                                            <TextField
                                                fullWidth
                                                margin="dense"
                                                id="newPriceField"
                                                //defaultValue={name != null ? name : ""}
                                                value={newArticle.price}
                                                onChange={(e) => setNewArticle({ ...newArticle, price: e.target.value })}
                                                error={(newArticle.price === 0)}
                                                label="Preis"
                                                type="number"
                                                variant="standard"
                                                InputProps={{
                                                    endAdornment: <InputAdornment position="end">€</InputAdornment>
                                                }}
                                            /> 
                                        </Grid>
                                        <Grid item xs={2}>
                                            <TextField
                                                width='10px'
                                                margin="dense"
                                                id="newMwSTField"
                                                //defaultValue={name != null ? name : ""}
                                                value={newArticle.MwSt}
                                                onChange={(e) => setNewArticle({ ...newArticle, MwSt: e.target.value })}
                                                label="MwSt"
                                                type="number"
                                                variant="standard"
                                                InputProps={{
                                                    endAdornment: <InputAdornment position="end">%</InputAdornment>
                                                }}
                                            /> 
                                        </Grid>
                                        <Grid item xs={2}>
                                            <FormControlLabel control={
                                                <Checkbox
                                                    label='Sale?'
                                                    checked={newArticle.inSale}
                                                    onChange={(e) => setNewArticle({ ...newArticle, inSale: !newArticle.inSale })}
                                                    inputProps={{ 'aria-label': 'controlled' }}
                                                />
                                            } label="Sale?" />
                                        </Grid>
                                    </Grid>
                                </DialogContent>
                                <DialogActions>
                                <Button onClick={handleNewEntryClose}>Abbrechen</Button>
                                <Button onClick={handleNewEntryAdd}>Hinzufügen</Button>
                                </DialogActions>
                            </Dialog>
                            <DataGrid 
                                rows={tableData}
                                columns={columns}
                                editMode="row"
                                //pageSize={15}
                                onCellClick={handleDataGridClick}
                                onCellDoubleClick={handleDataGridDoubleClick}
                                //onCellKeyDown={handleCellKeyDown}
                                rowModesModel={rowModesModel}
                                onRowModesModelChange={(model) => setRowModesModel(model)}
                                processRowUpdate={processRowUpdate}
                                
                                experimentalFeatures={{ newEditingApi: true }}
                                components={{
                                    Toolbar: EditToolbar,
                                }}
                                componentsProps={{
                                    toolbar: { 
                                        setArticles,
                                        setOpenNewEntryDialog 
                                    },

                                }}
                            />
                            <Grid container spacing={1}>
                                <Grid item xs={4}>
                                    <FormControl sx={{ m: 1, minWidth: 120 }}>
                                        <InputLabel>Zahlungsart</InputLabel>
                                        <Select
                                            
                                            id="payment_type"
                                            value={paymentType}
                                            label="Zahlungsart"
                                            onChange={(e) => {setPaymentType(e.target.value)}}
                                        >
                                            {paymentTypes.map((unit) => (
                                                <MenuItem
                                                key={unit}
                                                value={unit}
                                                //style={getStyles(name, personName, theme)}
                                                >
                                                {unit}
                                                </MenuItem>
                                            ))}
                                        </Select>    
                                        
                                    </FormControl>
                                </Grid>
                                <Grid item xs={6}>
                                    <TextField
                                        disabled
                                        fullWidth
                                        margin="dense"
                                        id="Gesamtpreis"
                                        value={totalPrice}
                                        onChange={(e) => setTotalPrice(e.target.value)}
                                        label="Gesamtpreis"
                                        type="number"
                                        variant="standard"
                                        /*
                                        inputProps: object
                                        Attributes applied to the input element.

                                        InputProps: object
                                        Props applied to the Input element. It will be a FilledInput, OutlinedInput or Input component depending on the variant prop value.
                                        */
                                        InputProps={{ endAdornment: <InputAdornment position="end">€</InputAdornment> }}
                                        inputProps={{ style: { textAlign: 'right' } }}
                                        //onBlur={(e) => handleArticleChangeAPI(e,'EAN', e.target.value)}
                                    />
                                </Grid>
                                <Grid item xs={2} alignItems="stretch" style={{ display: "flex" }}>
                                    <Button onClick={handleSavePrice}>
                                        Preis übernehmen
                                    </Button>
                                </Grid>
                            </Grid>
                            {!!snackbar && (
                                <Snackbar
                                    open
                                    anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
                                    onClose={handleCloseSnackbar}
                                    autoHideDuration={6000}
                                >
                                <Alert {...snackbar} onClose={handleCloseSnackbar} />
                                </Snackbar>
                            )} 
                        </div>
                    </div>  
                </Grid>

                <Grid item xs={4}>
                    <ReceipeCanvas 
                        setNewRect={setDrawData} 
                        image={img}
                        myRef={drawRef}
                    />
                </Grid>

        </Grid>
        
        </div>
        
        

    )
    
}

export default PurchaseDetails
