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

import {TextField, Autocomplete, createFilterOptions} from '@mui/material'
import Snackbar from '@mui/material/Snackbar';
import Alert from '@mui/material/Alert';

const filter = createFilterOptions();

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

const ListFieldApi = (props) => {

    const { apiURL, titleName, addName, multiple, value, onChange, sx, article, fieldName } = props
    
    const [list, setList] = useState([""]);
    const [inputValue, setInputValue] = React.useState('')
    const [snackbar, setSnackbar] = useState(null);

    const handleAdd = async(newValue) => {
        const send = await axios.post(baseURL+apiURL+'/', {
            name: newValue, 
        })
        
        const rec = await axios.get(baseURL+apiURL)
        
        setList(rec.data);
        
    };
    
    const handleCloseSnackbar = () => setSnackbar(null);

    const handleOnChange = async (event, newValue) => {
        //Neuer Wert ist letztes Array element
        //console.log(event)
        //console.log(newValue)
        if (newValue === null){
        }
        // Fall das wir mehr als einen Eintrag haben
        else if (Array.isArray(newValue)) {
            if (!(newValue.length === 0)){
                // Wenn letztes array element nicht in der Liste der möglichen, dann haben wir ein neues Element was wir hinzufügen
                if (!list.some(item => item.name === newValue[newValue.length - 1].name)) {
                    handleAdd(newValue[newValue.length - 1].inputValue);
                    newValue[newValue.length - 1].name = newValue[newValue.length - 1].inputValue;
                    delete newValue[newValue.length - 1]["inputValue"];
                    
                } 
            }
        }
        // Hinzufügen des ersten Elements
        else{
            if (!list.some(item => item.name === newValue.name)) {
                handleAdd(newValue.inputValue);
                newValue.name = newValue.inputValue;
                delete newValue["inputValue"];
            }
        }

        try {
            const newArticle = { ...article, [fieldName]: newValue};
            const sendArticle = await axios.put(baseURL+"/article/"+article.pk, {
                article: newArticle 
            });

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

            onChange(newArticle);
        }
        catch(error){
            setSnackbar({ children: error.message, severity: 'error' });
            if (Array.isArray(newValue)) {
                newValue = newValue.slice(0, -1);
            }
            else {
                newValue = null;
            }
        }
    }

    useEffect(()=>{      
        axios.get(baseURL+apiURL)
             .then((res) => {
                const data = res.data;
                setList(data);
                //console.log(data)
            })
       
    },[])
    
    return (
        <div>
        <Autocomplete
            multiple={multiple}
            id="tags-standard"
            options={list}
            sx={sx}
            getOptionLabel={(option) => {
                if (option.name === undefined){
                    return ""
                }
                else{
                    return option.name
                }
            }}
            isOptionEqualToValue={(option, value) => option.name === value.name}
            inputValue={inputValue}
            onInputChange={(_, newInputValue) => {
                setInputValue(newInputValue)
            }}
            //defaultValue={[]}
            value={value}
            renderInput={(params) => (
            <TextField
                {...params}
                variant="standard"
                label={titleName}
                placeholder={addName}
            />
            )}
            onChange={handleOnChange}
            filterOptions={(options, params) => {
                const filtered = filter(options, params);

                if (params.inputValue !== '') {
                    filtered.push({
                        inputValue: params.inputValue,
                        name: `Add "${params.inputValue}"`,
                    });
                }

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

export default ListFieldApi
