import { Box, Button, Container, CssBaseline, Grid, TextField, Typography } from "@mui/material"
import { useEffect, useState } from "react"
import { useGetProductQuery, useSetGoodUpsertMutation } from "../../../store/categoriesApi"
import ImageUploader from "../../ImageUploader"
import RecursiveTreeView from "./MuiTreeWithCheckBox"
import { useParams } from "react-router-dom"


const AdminGoodMutation = () => {
    const [selected, setSelect] = useState([])
    const [images, setImages] = useState([])
    const [stateGood, setStateGood] = useState({})

    const [GoodUpsert, result] = useSetGoodUpsertMutation()
    const { goodId } = useParams()
    const { data: payload = null } = useGetProductQuery(goodId)
    const good = payload ? Object.values(payload)[0] : null
    console.log("stateGood", stateGood)
    useEffect(() => {
       setStateGood(good)
       setSelect(good?.categories ? good?.categories.map((cat)=>cat._id) : [])
    }, [payload])


    console.log("selected", selected)



    const handlerGoodUpsert = (event) => {
        event.preventDefault();
        const data = new FormData(event.currentTarget);

        const goodToUpsert = {
            _id: stateGood._id,
            name: stateGood.name || null,
            price: +stateGood.price || null,
            description: stateGood.description || null,
            categories: selected.map(id => ({ _id: id })),
            images: images.map(image => ({ _id: image._id }))
        }
        console.log("goodToUpsert", goodToUpsert)
        GoodUpsert(goodToUpsert).then(res => console.log(res))
    }

    return (
        <>
            <Container component="main" maxWidth="sm">
                <CssBaseline />
                <Box
                    sx={{
                        marginTop: 2,
                        display: 'flex',
                        flexDirection: 'column',
                        alignItems: 'center',
                    }}
                >

                    <Typography component="h1" variant="h5">
                        Редактирование товара
                    </Typography>
                    <Box component="form" noValidate onSubmit={handlerGoodUpsert} sx={{ mt: 3 }}>
                        <Grid container spacing={2}>
                            <Grid item xs={12} sm={6}>
                                <TextField
                                    name="goodsName"
                                    required
                                    fullWidth
                                    id="goodsName"
                                    label="Название"
                                    autoFocus
                                    value={stateGood?.name || ""}
                                    onChange={ 
                                        (event) => setStateGood({...stateGood, name: event.target.value  })
                                        } 
                                ></TextField>
                            </Grid>
                            <Grid item xs={12} sm={6}>
                                <TextField
                                    required
                                    fullWidth
                                    id="goodsPrice"
                                    label="Цена, грн."
                                    name="goodsPrice"
                                    type={"number"}
                                    value={stateGood?.price || ""}
                                    onChange={ 
                                        (event) => setStateGood({...stateGood, price: event.target.value  })
                                        } 
                                />
                            </Grid>

                            <Grid item xs={12}>
                                <TextField
                                    fullWidth
                                    multiline
                                    rows={10}
                                    name="goodDescription"
                                    label="Описание"
                                    id="goodDescription"
                                    value={stateGood?.description || ""}
                                    onChange={ 
                                        (event) => setStateGood({...stateGood, description: event.target.value  })
                                        } 
                                />
                            </Grid>

                        </Grid>
                        <Grid item xs={12} mt={1}>
                            <Typography mb={2}>Измените категории: </Typography>
                            <Box maxHeight={"300px"} overflow={"scroll"}>
                            { stateGood?._id && <RecursiveTreeView
                                callback={(arr) => setSelect(arr)}
                                selectedCat={selected} />
                            }
                            </Box>
                        </Grid>
                        <Grid item xs={12} mt={1}>
                            <Typography mb={2}>Добавьте изображения товара или нажмите на фото для удаления:</Typography>
                            { stateGood?._id && <ImageUploader onChange={(images) => setImages(images)} passImages={stateGood?.images} />}
                        </Grid>

                        <Button
                            type="submit"
                            fullWidth
                            variant="contained"
                            sx={{ mt: 3, mb: 2 }}
                        >
                            Сохранить изменения
                        </Button>

                    </Box>
                </Box>
            </Container>

        </>

    )
}

export default AdminGoodMutation