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

import { Grid, TextField } from '@mui/material'
import Button from '@mui/material/Button'
import Snackbar from '@mui/material/Snackbar';
import Alert from '@mui/material/Alert';
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 FormControlLabel from '@mui/material/FormControlLabel';
import axios from 'axios';

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

const MarketDetail = (props) => {
    const [openExchangeDialog, setOpenExchangeDialog] = useState(false);
    const [exchangeMarket, setExchangeMarket] = useState({oldMarket: {}, newMarket: {name: '', street: '', street_number: 0, zip_code: '', city: '', phone:''}, deleteOld: false});
    const [markets, setMarkets] = useState([]);
    const [snackbar, setSnackbar] = useState(null);

    const [market, setMarket] = useState({
        name: '',
        street: '',
        street_number: 0,
        zip_code: '',
        city: '',
        phone: ''
    });

    useEffect(()=>{      
        axios.get(baseURL+"/market/"+props.marketId)
            .then((res) => {
                const data = res.data;
                //console.log(data)
                setMarket(data);
            })

        axios.get(baseURL+"/markets/")
            .then((res) => {
                console.log(res.data)
                setMarkets(res.data);
            })

    },[])
    


    const handleExchange = () => {
        setExchangeMarket({ ...exchangeMarket, oldMarket: market });
        setOpenExchangeDialog(true);
    }

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

    const handleMarketExchange = async () => {
        console.log(exchangeMarket)
        
        try {
            const receivedData = await axios.post(baseURL+"/exchangePurchaseMarket/"+props.purchaseId, {
                data: exchangeMarket, 
            })
            
            //const newData = tableData.map((row) => (row.id === exchangeArticle.oldRow.id ? receivedData.data : row));
            setMarket(exchangeMarket.newMarket);
            //const receivedData = null
            setSnackbar({ children: 'Änderungen erfolgreich gespeichert', severity: 'success' });


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

        }
        
    }

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

    const renderExchangeDialog = () => {
        return (
            <Dialog open={openExchangeDialog} onClose={handleExchangeClose}>
                <DialogTitle>Austausch eines Marketes gegen einen vorhandenen Markt</DialogTitle>
                <DialogContent>
                    <Grid container spacing={1}>
                        <Grid item xs={5} alignItems="stretch" style={{ display: "flex" }}>
                            Markt austauschen gegen:
                        </Grid>
                        <Grid item xs={7} alignItems="stretch" style={{ display: "flex" }}>
                        <Select
                            fullWidth
                            id="exchangeArticle"
                            value={exchangeMarket.newMarket.name}
                            label="Market"
                            onChange={(e,t) => {setExchangeMarket({...exchangeMarket, newMarket: markets.filter((element) => element.id === Number(t.key.replace('.$','')))[0] });}}
                        >
                            {markets.map((market) => (
                                <MenuItem
                                    key={market.id}
                                    value={market.name}
                                    //style={getStyles(name, personName, theme)}
                                >
                                {market.name+', '+market.street+' '+market.street_number+', '+market.city}
                                </MenuItem>
                            ))}
                        </Select>  
                        </Grid>
                        <FormControlLabel control={
                            <Checkbox
                                label='delete?'
                                checked={exchangeMarket.deleteOld}
                                onChange={(e) => {setExchangeMarket({ ...exchangeMarket, deleteOld: !exchangeMarket.deleteOld });}}
                                inputProps={{ 'aria-label': 'controlled' }}
                            />
                            } label="Ursprünglichen Artikel löschen?" 
                        />
                    </Grid>
                </DialogContent>
                <DialogActions>
                    <Button onClick={handleExchangeClose}>Abbrechen</Button>
                    <Button onClick={handleMarketExchange}>Änderung speichern</Button>
                </DialogActions>
            </Dialog>
        )
    }
    
    return(
        <Grid container spacing={1}>
            {renderExchangeDialog()}
            <Grid item xs={12}>
                <TextField
                    autoFocus
                    fullWidth
                    margin="dense"
                    id="name"
                    value={market.name}
                    /*
                    onChange={(event) =>
                        setMarket({
                            ...market,
                            name: event.target.value,
                    })
                    }
                    */
                    label="Name"
                    type="text"
                    variant="standard"
                />
            </Grid>
            <Grid item xs={9}>
                <TextField
                    margin="dense"
                    fullWidth
                    id="street"
                    value={market.street}
                    /*
                    onChange={(event) =>
                        setMarket({
                            ...market,
                            street: event.target.value,
                        })
                    }
                    */
                    label="Straße"
                    type="text"
                    variant="standard"
                />
            </Grid>
                <Grid item xs={2}>
                    <TextField
                        margin="dense"
                        id="streetnum"
                        fullWidth
                        value={market.street_number}
                        /*
                        onChange={(event) =>
                        setMarket({
                            ...market,
                            streetNum: event.target.value,
                        })
                        }
                        */

                        label="Nr."
                        type="number"
                        variant="standard"
                    />
                </Grid>
            <Grid item xs={4}>
                <TextField
                    margin="dense"
                    id="zip"
                    fullWidth
                    value={market.zip_code}
                    /*
                    onChange={(event) =>
                    setMarket({
                        ...market,
                        zip: event.target.value,
                    })
                    }
                    */
                    label="PLZ"
                    type="number"
                    variant="standard"
                />
            </Grid>
                <Grid item xs={8}>
                    <TextField
                        margin="dense"
                        id="city"
                        fullWidth
                        value={market.city}
                        /*
                        onChange={(event) =>
                        setMarket({
                            ...market,
                            city: event.target.value,
                        })
                        }
                        */
                        label="Stadt"
                        type="text"
                        variant="standard"
                    />
                </Grid>
                <Grid item xs={12}>
                    <TextField
                        margin="dense"
                        id="phone"
                        fullWidth
                        value={market.phone}
                        /*
                        onChange={(event) =>
                        setMarket({
                            ...market,
                            tel: event.target.value,
                        })
                        }
                        */
                        label="Telefon"
                        type="text"
                        variant="standard"
                    />
                </Grid>
                <Grid item xs={3}>
                <Button onClick={handleExchange}>Markt austauschen</Button>
                </Grid>
                {!!snackbar && (
                    <Snackbar
                        open
                        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
                        onClose={handleCloseSnackbar}
                        autoHideDuration={6000}
                    >
                    <Alert {...snackbar} onClose={handleCloseSnackbar} />
                    </Snackbar>
                )} 
            </Grid>
            
    )
}

export default MarketDetail
                        
