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"

/*
    - Crashes if deleting an entry
*/
  
function EditToolbar(props) {
    const { setTableData, article } = props;

    const handleClick = async () => {

        const newValue = {id: Math.floor(Math.random() * 1000)+10, value: 0, isEstimated: false, unit: 'g'}

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

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

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

const NutriDataGrid = (props) => {
    const { article } = props;
    
    const [tableData, setTableData] = useState([{id: -1, type: '', serving: 0, unit: 'g'}]);
    const [options, setOptions] = useState([{id: -1, name: ''}]);

    const [snackbar, setSnackbar] = useState(null);

    const units = ['kg','g','mg','µg','l','ml','St','kJ','kcal'];

    const columns = [
        {
            field: 'isEstimated',
            headerName: 'Schätzung?',
            width: 100,
            editable: true,
            type: 'boolean',
        },
        {
            field: 'nutrient', 
            headerName: 'Nährwert',
            width:150,
            type: 'singleSelect',
            //valueOptions: () => {return options.map(x => x.name)},
            valueOptions: options,
            getOptionValue: (value) => value.id,
            getOptionLabel: (value) => value.name,
            editable: true,
            flex: 1,
            valueGetter: (params) => {try {return params.row.nutrient.id;} catch {return '';} },
        },
        {
            field: 'value', 
            headerName: '100g/100ml', 
            editable: true,
            type: 'number',
            //valueGetter: (params) => { return params.row.data.serving },
        },
        {
            field: 'unit', 
            headerName: 'Einheit', 
            type: 'singleSelect',
            valueOptions: units,
            editable: true,
            //valueGetter: (params) => { return params.row.data.unit },
        },
        /*
        {field: 'portion', headerName: 'Portion'},
        */
        {
            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 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);

        try {
            const receivedData = await axios.delete(baseURL+"/article/nutritionalValues/"+article.pk, {
                data: id, 
            })
            setSnackbar({ children: 'Nährwert erfolgreich gelöscht', severity: 'success' });
            setTableData(newData);
        } catch (error) {
            setSnackbar({ children: error.message, severity: 'error' });
        }
      };
    
    const processRowUpdate = React.useCallback( async (newRow, oldRow) => {
        console.log(newRow)

        var nutrient;
        if (newRow.nutrient === undefined) {
            return newRow;
        }
        else if (typeof newRow.nutrient === 'number') {
            nutrient = options.find(x => x.id === newRow.nutrient);
        }
        else {
            nutrient = newRow.nutrient;
        }

        const updatedRow = {id: newRow.id, article_id: article.pk, nutrient: nutrient, value: newRow.value, unit: newRow.unit, isEstimated: newRow.isEstimated, isNew: false};
        const newData = tableData.map((row) => (row.id === newRow.id ? updatedRow : row));
        //console.log(newData)
        try {
            //const newCompleteData = {article: article.pk, data: newData, id: id};
            //console.log(newCompleteData)
            const response = await axios.put(baseURL+"/article/nutritionalValues/"+article.pk, {
                nutriData: 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(() =>{
        async function fetchOptions() {
            const ans = await axios.get(baseURL+"/article/nutrients/");
            setOptions(ans.data);
        }

        async function fetchData() {
            const values = await axios.get(baseURL+"/article/nutritionalValues/"+article.pk);
            setTableData(values.data);
        }
        fetchOptions();
        fetchData();
        
    },[article])
    
    return (
        <div style={{ height: 570, width: '100%' }}>
            <DataGrid 
                rows={tableData}
                columns={columns}
                pageSize={10}
                editMode="cell"
                //getRowId={(row) => row.internalId}
                processRowUpdate={processRowUpdate}
                //onProcessRowUpdateError={handleProcessRowUpdateError}
                //isCellEditable={(params) => {console.log(params);return !permanentOptions.includes(params.field) }}
                experimentalFeatures={{ newEditingApi: true }}
                components={{
                    Toolbar: EditToolbar,
                }}
                componentsProps={{
                    toolbar: { setTableData, article },
                }}
                initialState={{
                    sorting: {
                      sortModel: [{ field: 'id', sort: 'desc' }],
                    },
                  }}

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

export default NutriDataGrid
