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

import axios from 'axios';

import { useLocation } from 'react-router-dom';

import { Grid, Typography, TextField, Select, MenuItem, Stack} from '@mui/material'
import { Button, Paper, styled, } from '@mui/material'
import Box from '@mui/material/Box';
import { grey } from '@mui/material/colors';

import Snackbar from '@mui/material/Snackbar';
import Alert from '@mui/material/Alert';

//import ReceipeCanvas from "./Canvas.component"
import CategoryTree from "./CategoryTree.component"
import ListFieldApi from "./ListFieldApi.component"
import PackagingDataGrid2 from "./PackagingDataGrid2.component"
import NutriDataGrid from "./NutriDataGrid.component"
import PictureCard from "./pictureCard.component"
import IngredienceDataGrid from "./IngredienceDataGrid.component"

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

const Item = styled(Paper)(({ theme }) => ({
  backgroundColor: theme.palette.mode === 'dark' ? '#1A2027' : '#fff',
  ...theme.typography.body2,
  padding: theme.spacing(1),
  textAlign: 'center',
  color: theme.palette.text.secondary,
}));

//article is pushed from PurchaseDetail.component
const ArticleDetails = (props) => {
    const location = useLocation();
    var earlyExit = false;
    if (location.state != null){ 
        console.log(location)
        console.log(location.state.id)
        console.log(location.state.article_id)
    }
    else {
        console.log("No data to show");
        console.log(location)
        location.state = {'article_id': {'name': '','EAN':'', 'brand':''}};
        console.log(location)
        earlyExit = true;
    }
    
    const units = ['kg','g','l','ml','St.','kJ','kcal','µg'];
    const grades = ['','A','B','C','D','E'];
    const novas = ['','1','2','3','4'];
    
    const [article, setArticle] = useState(location.state.article_id);
    const [name, setName] = useState(article.name);
    const [EAN, setEAN] = useState(article.EAN);
    const [offlink, setOfflink] = useState(article.offlink);
    const [quantityPerPackage, setQuantityPerPackage] = useState(article.quantityPerPackage);
    const [unit, setUnit] = useState(article.unit);
    //const [nutritionGrade, setNutritionGrade] = useState(article.nutritionGrade);
    //const [novaGroup, setNovaGroup] = useState(article.novaGroup);
    //const [ecoGrade, setEcoGrade] = useState(article.ecoGrade);

    const [snackbar, setSnackbar] = useState(null);
    
    const EANvalid = () => {
        if (EAN === null) 
            return false; 
        else {
            if (EAN.length === 13 || EAN.length === 8) {
                return true;
            } else {
                return false;
            }
        }
    }

    const handleSearchButton = async () => {
        try {
            const ans = await axios.get(baseURL+"/offsearch_get_by_ean/"+EAN+"/"+article.pk, { });
            
            //setArticle(ans.data.article);
            const newArticle = ans.data;
            setArticle(newArticle);
            
            //console.log('New Article:')
            //console.log(newArticle)
            location.state.article_id = newArticle;
            setSnackbar({ children: 'Daten erfolgreich übernommen', severity: 'success' });

        }
        catch(error){
            setSnackbar({ children: error.message, severity: 'error' });
        }
    };
       
    const handelArticleChange = (value) => {
        setArticle(value);
    }

    const handleArticleChangeAPI = async (event, field, value) => {
        try {
            if (field === 'nutritionGrade' || field === 'novaGroup' || field === 'ecoGrade'){
                console.log(value)
                const newArticle = { ...article, [field]: value};
                const sendArticle = await axios.put(baseURL+"/article/"+article.pk, {
                    article: newArticle 
                });
                setArticle(newArticle);
            }
            else {

                const newArticle = { ...article, [field]: value};
                const sendArticle = await axios.put(baseURL+"/article/"+article.pk, {
                    article: newArticle 
                });
                setArticle(newArticle);
            }

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

            
        }
        catch(error){
            setSnackbar({ children: error.message, severity: 'error' });
            setName(eval('article.'+field));
        }
        
    }

    
    const handleCloseSnackbar = () => setSnackbar(null);
    
    if (earlyExit){
        return(<div> </div>);
    }
    
    return (
        <Grid container spacing={1}>
                <Grid item xs={12}>
                  <Typography variant="h3" component="div" gutterBottom>
                    {article.brand === null ? '': article.brand.name} {" "+ article.name}
                  </Typography>
                </Grid>
               
               <Grid item xs={12}>
                    <TextField
                        fullWidth
                        margin="dense"
                        id="nameField"
                        //defaultValue={name != null ? name : ""}
                        value={name}
                        onChange={(e) => setName(e.target.value)}
                        error={(article.name.length === 0)}
                        label="Name"
                        type="text"
                        variant="standard"
                        onBlur={(e) => handleArticleChangeAPI(e,'name', e.target.value)}
                    />

                </Grid>
               
                <Grid item xs={12}>
                    <TextField
                        //autoFocus
                        fullWidth
                        margin="dense"
                        id="EAN"
                        value={EAN != null ? EAN : "" }
                        onChange={(e) => setEAN(e.target.value)}
                        error={!EANvalid()}  
                        label="EAN/EAN-13"
                        type="number"
                        variant="standard"
                        onBlur={(e) => handleArticleChangeAPI(e,'EAN', e.target.value)}
                    />
                </Grid>
                
                <Grid item xs={12}>
                    <TextField
                        //autoFocus
                        fullWidth
                        margin="dense"
                        id="offlink"
                        value={offlink != null ? offlink : ""}
                        onChange={(e) => setOfflink(e.target.value)}
                        label="OpenFoodFact Link"
                        type="text"
                        variant="standard"
                        onBlur={(e) => handleArticleChangeAPI(e,'offlink', e.target.value)}
                    />
                </Grid>
                
                <Grid item xs={4}>
                    <Button variant="contained"
                            onClick={handleSearchButton}
                            disabled={!EANvalid()}
                    >
                        EAN bei OpenFoodFact suchen
                    </Button>
                </Grid>
                
       {/*-----------------------------------------------------------------------------------*/}
       {/*-----------------------------------------------------------------------------------*/}
                <Grid item xs={12}>
                  <Typography variant="h4" component="div" gutterBottom textAlign="center">
                    Produkteigenschaften
                  </Typography>
                </Grid>
                <Grid item xs={4}>
                        <PictureCard
                            type="Artikelbild"
                            article={article}
                            pictureType="frontImage"
                            onChange={handelArticleChange}
                        >    
                        </PictureCard>
                </Grid>
                <Grid item xs={8}>
                    <Grid container spacing={1}>
                        <Grid item xs={12}>
                            <ListFieldApi 
                                apiURL="/article/brands/" 
                                titleName="Marke" 
                                addName="Marke" 
                                multiple={false}
                                value={article.brand} 
                                onChange={handelArticleChange}
                                article={article}
                                fieldName={'brand'}
                            />
                        </Grid>
                        
                        <Grid item xs={10}>
                            <TextField
                                //autoFocus
                                fullWidth
                                margin="dense"
                                id="quantityPerPackage"
                                value={quantityPerPackage != null ? quantityPerPackage : ""}
                                onChange={(e) => setQuantityPerPackage(e.target.value)}
                                label="Mengenangabe"
                                type="number"
                                variant="standard"
                                onBlur={(e) => handleArticleChangeAPI(e,'quantityPerPackage',e.target.value)}
                            />
                        </Grid>
                        <Grid item xs={2}>
                            <Select
                                fullWidth
                                id="unit"
                                value={unit}
                                label="Einheit"
                                onChange={(e) => {setUnit(e.target.value);handleArticleChangeAPI(e,'unit',e.target.value)}}
                            >
                                {units.map((unit) => (
                                    <MenuItem
                                    key={unit}
                                    value={unit}
                                    //style={getStyles(name, personName, theme)}
                                    >
                                    {unit}
                                    </MenuItem>
                                ))}
                            </Select>    
                        </Grid>

                        <Grid item xs={12}>
                            <Typography variant="subtitle1" component="div" gutterBottom>
                                Verpackung
                            </Typography>
                        </Grid>
                        <Grid item xs={12}>
                            <PackagingDataGrid2 
                                articleId={article.pk}
                            />
                        </Grid>
                        
                        <Grid item xs={12}>
                            <ListFieldApi 
                                apiURL="/article/labels/" 
                                titleName="Kennzeichnungen" 
                                addName="Label" 
                                multiple={true}
                                value={article.labels} 
                                onChange={handelArticleChange}
                                article={article}
                                fieldName={'labels'}
                            />
                        </Grid>
                        <Grid item xs={12}>
                            <Typography variant="subtitle1" component="div" gutterBottom>
                                Kategorie
                            </Typography>
                        </Grid>
                        <Grid item xs={12}>
                            <Box sx={{ borderRadius: '10px', p: 2, border: '1px solid', borderColor: grey[300] }}>
                            <CategoryTree 
                                value={article.category}
                                onChange={handelArticleChange}
                                article={article}
                            />
                            </Box>
                        </Grid>
                        <Grid item xs={12}>
                            <Typography variant="subtitle1" component="div" gutterBottom>
                                Scors
                            </Typography>
                        </Grid>
                        <Grid item xs={12}>
                            <Stack direction="row" spacing={2}>
                                <Item>
                                    <Select
                                        fullWidth
                                        labelId="nutriSelect"
                                        id="nutri"
                                        value={article.nutritionGrade === null ? '' : article.nutritionGrade}
                                        label="Nutri-Score"
                                        onChange={(e) => {const value = e.target.value; 
                                                          //setNutritionGrade(typeof value === 'string' ? value.split(',') : value); 
                                                          handleArticleChangeAPI(e,'nutritionGrade', value)
                                                        }
                                                }
                                    >
                                        {grades.map((grade) => (
                                            <MenuItem
                                            key={grade}
                                            value={grade}
                                            //style={getStyles(name, personName, theme)}
                                            >
                                            {grade}
                                            </MenuItem>
                                        ))}
                                    </Select>  
                                    <img width={'100%'} src={"http://127.0.0.1:8080/Nutri-score-"+article.nutritionGrade+".svg"} alt="NutriScore"/>
                                </Item>
                                <Item>
                                    <Select
                                        fullWidth
                                        labelId="nutriSelect"
                                        id="nova"
                                        value={article.novaGroup === null ? '' : article.novaGroup}
                                        label="NovaGroup"
                                        onChange={(e) => {const value = e.target.value; 
                                                        //setNovaGroup(typeof value === 'string' ? value.split(',') : value); 
                                                        handleArticleChangeAPI(e,'novaGroup', value)
                                                    }
                                            }
                                    >
                                        {novas.map((grade) => (
                                            <MenuItem
                                            key={grade}
                                            value={grade}
                                            //style={getStyles(name, personName, theme)}
                                            >
                                            {grade}
                                            </MenuItem>
                                        ))}
                                    </Select>  
                                    <img width={'100%'} src={"http://127.0.0.1:8080/nova-group-"+article.novaGroup+".svg"} alt="NovaGroup"/>
                                </Item>
                                <Item>
                                    <Select
                                        fullWidth
                                        labelId="nutriSelect"
                                        id="eco"
                                        value={article.ecoGrade === null ? '' : article.ecoGrade}
                                        label="EcoGrade"
                                        onChange={(e) => {const value = e.target.value; 
                                                        //setEcoGrade(typeof value === 'string' ? value.split(',') : value); 
                                                        handleArticleChangeAPI(e,'ecoGrade', value)
                                                    }
                                            }
                                    >
                                        {grades.map((grade) => (
                                            <MenuItem
                                            key={grade}
                                            value={grade}
                                            //style={getStyles(name, personName, theme)}
                                            >
                                            {grade}
                                            </MenuItem>
                                        ))}
                                    </Select> 
                                    <img width={'100%'} src={"http://127.0.0.1:8080/Eco-score-"+article.ecoGrade+".svg"} alt="EcoGrade"/>
                                </Item>
                            </Stack>
                            
                        </Grid>
                        
                    </Grid>
                    
                </Grid>
                
          {/*-----------------------------------------------------------------------------------*/}
          {/*-----------------------------------------------------------------------------------*/}            
                <Grid item xs={12}>
                <Typography variant="h4" component="div" gutterBottom textAlign="center">
                    Inhaltsstoffe
                </Typography>
                </Grid>
                <Grid item xs={4}>
                    <PictureCard
                        type="Bild der Inhaltsstoffe"
                        article={article}
                        pictureType="ingredientsImage"
                        onChange={handelArticleChange}
                    >    
                    </PictureCard>
                </Grid>
                <Grid item xs={8}>       
                        <Grid item xs={12}>
                            {/*
                            <ListFieldApi 
                                apiURL="/article/ingrediences" 
                                titleName="Inhaltsstoffe" 
                                addName="Zutat"
                                multiple={true}
                                value={article.ingredients} 
                                onChange={handelArticleChange}
                                article={article}
                                fieldName={'ingredients'}
                            />
                            */}
                            <IngredienceDataGrid 
                                articleId={article.pk}
                            />
                        </Grid>
                        
                        <Grid item xs={12}>
                            <ListFieldApi 
                                apiURL="/article/allergenes/" 
                                titleName="Allergene" 
                                addName="Zutat"
                                multiple={true}
                                value={article.allergenes} 
                                onChange={handelArticleChange}
                                article={article}
                                fieldName={'allergenes'}
                            />
                        </Grid>
                        
                        <Grid item xs={12}>
                            <ListFieldApi 
                                apiURL="/article/traces/" 
                                titleName="Spuren" 
                                addName="Zutat" 
                                multiple={true}
                                value={article.traces} 
                                onChange={handelArticleChange}
                                article={article}
                                fieldName={'traces'}
                            />
                        </Grid>
                        
                        <Grid item xs={12}>
                            <ListFieldApi 
                                apiURL="/article/embs/" 
                                titleName="EMB Nummern" 
                                addName="Nummer" 
                                multiple={true}
                                value={article.embs} 
                                onChange={handelArticleChange}
                                article={article}
                                fieldName={'embs'}
                            />
                        </Grid>
                        
                        <Grid item xs={12}>
                            <ListFieldApi 
                                apiURL="/article/manufacturingPlaces/" 
                                titleName="Ort der Herstellung" 
                                addName="Ort" 
                                multiple={true}
                                value={article.manufacturingPlaces} 
                                onChange={handelArticleChange}
                                article={article}
                                fieldName={'manufacturingPlaces'}
                            />
                        </Grid>
                        
                        <Grid item xs={12}>
                            <ListFieldApi 
                                apiURL="/article/originIngredients/" 
                                titleName="Herkunft der Inhaltsstoffe" 
                                addName="Ort" 
                                multiple={true}
                                value={article.originIngredients} 
                                onChange={handelArticleChange}
                                article={article}
                                fieldName={'originIngredients'}
                            />
                        </Grid>
                </Grid>
            {/*-----------------------------------------------------------------------------------*/}
            {/*-----------------------------------------------------------------------------------*/}

                <Grid item xs={12}>
                  <Typography variant="h4" component="div" gutterBottom textAlign="center">
                    Nährwertangaben
                  </Typography>
                </Grid>
                <Grid item xs={4}>
                    <PictureCard
                        type="Bild der Nährwerte"
                        article={article}
                        pictureType="nutritionImage"
                        onChange={handelArticleChange}
                    >    
                    </PictureCard>
                </Grid>
                <Grid item xs={8}>
                    <NutriDataGrid 
                        article={article}
                    />
                </Grid>
                <div>
                    {!!snackbar && (
                    <Snackbar
                    open
                    anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
                    onClose={handleCloseSnackbar}
                    autoHideDuration={6000}
                    >
                    <Alert {...snackbar} onClose={handleCloseSnackbar} />
                    </Snackbar>
                )}
                </div>
        </Grid>

    )
}

export default ArticleDetails
