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, Autocomplete, TextField } from '@mui/material'

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

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

import ListFieldApi from "./ListFieldApi.component"

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


const makeId = () => {
  let ID = "";
  let characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  for ( var i = 0; i < 12; i++ ) {
    ID += characters.charAt(Math.floor(Math.random() * 36));
  }
  return ID;
}

const EditToolbar = (props) => {
  const { onChange, setRowModesModel, setList } = props;

  const [inputValue, setInputValue] = React.useState('')
  
  const handleClick = () => {
    const id = makeId();
    onChange([{ id, packaging: '', weight: '', isNew: true }]);
    setRowModesModel((oldModel) => ({
      ...oldModel,
      [id]: { mode: GridRowModes.Edit, fieldToFocus: 'packaging' },
    }));
  };
  
  const handelMaterialChange = (event) => {
    if (event == null){
        setInputValue('')
    }
    else{
        setInputValue(event.name);
    }
    //axios.get(baseURL+apiURL)
    //         .then((res) => {
    //            const data = res.data;
    //            setList(data);
    //            //console.log(data)
    //        })
  } 

  return (
    <GridToolbarContainer>
      <Button color="primary" startIcon={<AddIcon />} onClick={handleClick}>
        Eintrag hinzufügen
      </Button>
      <ListFieldApi 
        apiURL={apiURL} 
        titleName="Material hinzufügen" 
        addName="Material" 
        multiple={false}
        value={inputValue} 
        onChange={handelMaterialChange}
        sx={{ width: 300 }}
      />
    </GridToolbarContainer>
  );
}

EditToolbar.propTypes = {
  setRowModesModel: PropTypes.func.isRequired,
  onChange: PropTypes.func.isRequired,
};

const initialRows = [
  {
    id: makeId(),
    packaging: 'Pappe',
    weight: 0,
  },
]

const PackagingDataGrid = (props) => {
    
    const { value, onChange, setArticle,...rest } = props;
    const [rows, setRows] = React.useState([]);
    const [rowModesModel, setRowModesModel] = React.useState({});
    const [list, setList] = useState([]);
    const [inputValue, setInputValue] = React.useState('')
    
    const columnsPackaging = [
        {
            field: 'packaging', 
            headerName: 'Material',
            width: 350,
            type: 'singleSelect',
            valueOptions: () => {return list.map(x => x.name)},
            editable: true,
        },
        {
            field: 'weight', 
            headerName: 'Gewicht in g', 
            type: 'number',
            width:100,
            editable: true,
        },
        {
            field: 'actions',
            type: 'actions',
            headerName: 'Actions',
            width: 150,
            cellClassName: 'actions',
            getActions: ({ id }) => {
                const isInEditMode = rowModesModel[id]?.mode === GridRowModes.Edit;

                if (isInEditMode) {
                return [
                    <GridActionsCellItem
                    icon={<SaveIcon />}
                    label="Save"
                    onClick={handleSaveClick(id)}
                    />,
                    <GridActionsCellItem
                    icon={<CancelIcon />}
                    label="Cancel"
                    className="textPrimary"
                    onClick={handleCancelClick(id)}
                    color="inherit"
                    />,
                ];
                }

                return [
                <GridActionsCellItem
                    icon={<EditIcon />}
                    label="Edit"
                    className="textPrimary"
                    onClick={handleEditClick(id,rows)}
                    color="inherit"
                />,
                <GridActionsCellItem
                    icon={<DeleteIcon />}
                    label="Delete"
                    onClick={handleDeleteClick(id)}
                    color="inherit"
                />,
                ];
            },
        },
    ]
 
    //const handleRowEditStart = (params, event) => {
    //    event.defaultMuiPrevented = true;
    //};

    const handleRowEditStop = (params, event) => {
        event.defaultMuiPrevented = true;
    };

    const handleEditClick = (id, rows) => () => {
        console.log(rowModesModel)
        setRowModesModel({ ...rowModesModel, [id]: { mode: GridRowModes.Edit } });
    };

    const handleSaveClick = (id) => () => {
        setRowModesModel({ ...rowModesModel, [id]: { mode: GridRowModes.View } });
    };

    const handleDeleteClick = (id) => () => {
        setRows(rows.filter((row) => row.id !== id));
    };

    const handleCancelClick = (id) => () => {
        setRowModesModel({
        ...rowModesModel,
        [id]: { mode: GridRowModes.View, ignoreModifications: true },
        });

        const editedRow = rows.find((row) => row.id === id);
        if (editedRow.isNew) {
        setRows(rows.filter((row) => row.id !== id));
        }
    };

    const processRowUpdate = (newRow) => {
        const updatedRow = { ...newRow, isNew: false };
        console.log(newRow)
        setRows(rows.map((row) => (row.id === newRow.id ? updatedRow : row)));
        return updatedRow;
    };
    
    useEffect(()=>{      
        axios.get(baseURL+apiURL)
             .then((res) => {
                const data = res.data;
                setList(data);
                //console.log(data)
            })
       
    },[])
 
    return (
        <DataGrid 
            rows={value}
            columns={columnsPackaging}
            pageSize={10}
            editMode="row"
            rowModesModel={rowModesModel}
            //onRowEditStart={handleRowEditStart}
            onRowEditStop={handleRowEditStop}
            processRowUpdate={processRowUpdate}
            components={{
                Toolbar: EditToolbar,
            }}
            componentsProps={{
                toolbar: { onChange, setRowModesModel, setList },
            }}
            experimentalFeatures={{ newEditingApi: true }}
            //onRowEditStop={handleRowEditStop}
            //checkboxSelection
            //disableSelectionOnClick
            //onCellClick={handleDataGridClick}
            //onCellDoubleClick={handleDataGridDoubleClick}
        />
        
    );
}

export default PackagingDataGrid
