import {Autocomplete, createFilterOptions } from '@mui/material';
import { Button, Grid } from '@mui/material'
import {Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, TextField } from '@mui/material'
import {React, useState, useEffect, Fragment} from 'react'

import axios from 'axios';

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

const filter = createFilterOptions();

const SelectMarketField = () => {
    const [value, setValue] = useState(null);
    const [open, toggleOpen] = useState(false);
    const [optionData, setOptionData] = useState([]);

    const handleClose = () => {
        //setDialogValue({
        //    name: '',
        //    street: '',
        //});
        console.log(dialogValue)
        axios.post(baseURL+'/markets/', {
            name: dialogValue.name, 
            street: dialogValue.street, 
            street_number: dialogValue.streetNum, 
            zip_code: dialogValue.zip, 
            city: dialogValue.city, 
            phone: dialogValue.phone
        })
        .then(function (response) {
            console.log(response);
        })
        .catch(function (error) {
            console.log(error);
        });
        axios.get(baseURL+"/market")
        .then((res) => {
            const data = res.data;
            setOptionData(data);
        })
        .then(function (res) {
            console.log(res);
        })
        .catch(function (error) {
            console.log(error);
        });
        toggleOpen(false);
    };

    const [dialogValue, setDialogValue] = useState({
        name: '',
        street: '',
        streetNum: 0,
        zip: '',
        city: '',
        phone: ''
    });

    const handleSubmit = (event) => {
        event.preventDefault();
        setValue({
            name: dialogValue.name,
            street: dialogValue.street,
            streetNum: parseInt(dialogValue.streetNum,10),
            zip: parseInt(dialogValue.zip,10),
            city: dialogValue.city,
            phone: dialogValue.phone
        });

        handleClose();
    };
    
    useEffect(()=>{      
        axios.get(baseURL+"/markets")
            .then((res) => {
                const data = res.data;
                //console.log(data)
                setOptionData(data);
            })
    },[])

    return (
        <Fragment>
            <Autocomplete
                value={value}
                onChange={(event, newValue) => {
                    if (typeof newValue === 'string') {
                    // timeout to avoid instant validation of the dialog's form.
                    setTimeout(() => {
                        toggleOpen(true);
                        console.log('this')
                        setDialogValue({
                            name: newValue,
                            street: '',
                            streetNum: 0,
                            zip: '',
                            city: '',
                            phone: ''
                        });
                    });
                    } 
                    else if (newValue && newValue.inputValue) {
                        toggleOpen(true);
                        setDialogValue({
                            name: newValue.inputValue,
                            street: '',
                            streetNum: 0,
                            zip: '',
                            city: '',
                            phone: ''
                        });
                    } 
                    else {
                        setValue(newValue);
                    }
                }}
                filterOptions={(options, params) => {
                    const filtered = filter(options, params);

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

                    return filtered;
                }}
                id="free-solo-dialog"
                options={optionData}
                getOptionLabel={(option) => {
                    // e.g value selected with enter, right from the input
                    if (typeof option === 'string') {
                        return option;
                    }
                    if (option.inputValue) {
                        return option.inputValue;
                    }
                    return option.name;
                }}
                selectOnFocus
                clearOnBlur
                handleHomeEndKeys
                renderOption={(props, option) => <li {...props}>{option.name}</li>}
                sx={{ width: 300 }}
                freeSolo
                renderInput={(params) => <TextField {...params} label="Markt auswählen" />}
            />
            <Dialog open={open} onClose={handleClose}>
            <form onSubmit={handleSubmit}>
                <DialogTitle>Neuen Markt hinzufügen</DialogTitle>
                <DialogContent>
                <DialogContentText>
                    Ist der Markt noch nicht in der Liste? Dann füge ihn hinzu.
                </DialogContentText>
                <Grid container spacing={1}>
                    <Grid item xs={12}>
                        <TextField
                            autoFocus
                            fullWidth
                            margin="dense"
                            id="name"
                            error={dialogValue.name === ''}
                            value={dialogValue.name}
                            onChange={(event) =>
                                setDialogValue({
                                    ...dialogValue,
                                    name: event.target.value,
                            })
                            }
                            label="Name"
                            type="text"
                            variant="standard"
                        />
                    </Grid>
                    <Grid item xs={9}>
                        <TextField
                            margin="dense"
                            fullWidth
                            id="street"
                            error={dialogValue.street === ''}
                            //value={dialogValue.street}
                            onChange={(event) =>
                                setDialogValue({
                                    ...dialogValue,
                                    street: event.target.value,
                                })
                            }
                            label="Straße"
                            type="text"
                            variant="standard"
                        />
                    </Grid>
                        <Grid item xs={2}>
                            <TextField
                                margin="dense"
                                id="streetnum"
                                fullWidth
                                //value={dialogValue.streetNum}
                                error={dialogValue.streetNum === 0}
                                onChange={(event) =>
                                setDialogValue({
                                    ...dialogValue,
                                    streetNum: event.target.value,
                                })
                                }
                                label="Nr."
                                type="number"
                                variant="standard"
                            />
                        </Grid>
                    <Grid item xs={4}>
                        <TextField
                            margin="dense"
                            id="zip"
                            fullWidth
                            error={dialogValue.zip === ''}
                            //helperText="Incorrect entry."
                            //value={dialogValue.zip}
                            onChange={(event) =>
                            setDialogValue({
                                ...dialogValue,
                                zip: event.target.value,
                            })
                            }
                            label="PLZ"
                            type="number"
                            variant="standard"
                        />
                    </Grid>
                        <Grid item xs={8}>
                            <TextField
                                margin="dense"
                                id="city"
                                fullWidth
                                error={dialogValue.city === ''}
                                //value={dialogValue.city}
                                onChange={(event) =>
                                setDialogValue({
                                    ...dialogValue,
                                    city: event.target.value,
                                })
                                }
                                label="Stadt"
                                type="text"
                                variant="standard"
                            />
                        </Grid>
                        <Grid item xs={12}>
                            <TextField
                                margin="dense"
                                id="phone"
                                fullWidth
                                //value={dialogValue.tel}
                                onChange={(event) =>
                                setDialogValue({
                                    ...dialogValue,
                                    tel: event.target.value,
                                })
                                }
                                label="Telefon"
                                type="text"
                                variant="standard"
                            />
                        </Grid>
                </Grid>
                </DialogContent>
                <DialogActions>
                <Button 
                    onClick={handleClose}
                >
                    Abbrechen
                </Button>
                <Button 
                    type="submit"
                    disabled={dialogValue.name === "" ||
                              dialogValue.street === "" ||
                              dialogValue.streetNum === 0 ||  
                              dialogValue.zip === "" ||
                              dialogValue.city === ""
                    }
                >
                    Hinzufügen</Button>
                </DialogActions>
            </form>
            </Dialog>
        </Fragment>
    );
}

export default SelectMarketField
