import { ShoppingBasket } from "@mui/icons-material"
import { Box, Button, Divider, Drawer, InputAdornment, List, ListItem, ListItemIcon, ListItemText, TextField, Typography } from "@mui/material"
import { lightGreen } from "@mui/material/colors"
import { useDispatch, useSelector } from "react-redux"
import { Link } from "react-router-dom"
import { CartAdd, CartClear, CartDel, CartIncOne, CartSet } from "../store/cartSlice"
import { actionOrderUpsert } from "./actions/actions"

const Basket = (props) => {
    const {
        cartOpen,
        closeCart = Function.prototype,
    } = props

    const cartState = Object.values(useSelector(state => state.cart))
    const cartStateForOrderUpsert = cartState.map(
        (value) => {
            return {
                count: value.count,
                good: {_id: value.good._id}
            }
        }
        )
        console.log (cartStateForOrderUpsert)
    const userAuth = useSelector((state) => state.auth.user)

    const dispatch = useDispatch()

    const productsRender = ({ good, count }) => {

        return (
            <ListItem key={good._id} sx={{ display: "block" }}>
                <Box sx={{ margin: '10px 5px' }}>
                    <div style={{
                        height: '50px',
                        width: '50px',
                        backgroundSize: 'contain',
                        backgroundRepeat: 'no-repeat',
                        backgroundPosition: 'center',
                        backgroundImage: `url(${good?.images ? `http://shop-roles.node.ed.asmer.org.ua/${good.images[0].url}` : "https://archive.org/download/no-photo-available/no-photo-available.png"})`
                    }}></div>
                    <div>{good.name}</div>
                </Box>
                <Box>
                    <Button variant="outlined" size="small" onClick={() => dispatch(CartAdd({ good }))} sx={{ height: "40px", margin: "3px" }}>+</Button>
                    <TextField
                        size="small"
                        sx={{ height: "40px", width: "120px", margin: "3px" }}
                        type="number"
                        value={count}
                        InputProps={{
                            endAdornment: <InputAdornment position="start">шт</InputAdornment>,
                            inputProps: { min: "1", step: "1" },
                        }}
                        onChange={(e) => dispatch(CartSet({ good, count: e.target.value }))}
                    >

                    </TextField>
                    <Button
                        variant="outlined"
                        size="small"
                        onClick={() => dispatch(CartIncOne({ good }))}
                        disabled={count <= 1 ? true : false}
                        sx={{ height: "40px", margin: "3px" }}
                    >-</Button>
                    <Button variant="outlined" size="small" onClick={() => dispatch(CartDel({ good }))} sx={{ height: "40px", margin: "3px" }}>удалить</Button>
                </Box>
                <Divider sx={{ marginTop: "20px" }} />
            </ListItem>
        )
    }

    {/* cartState.map((product) => (
                        <div key={Math.random()}>
                            <Box sx={{ margin: '10px 5px' }}>
                                <div>_id: {product._id}</div>
                                <div>name: {product.name}</div>
                                <div>количество: {product.count}</div>
                            </Box>
                            <Box>
                                <Button variant="outlined" size="small" onClick={() => dispatch(CartAdd(product))}>+</Button>
                                <TextField
                                    size="small"
                                    type="number"
                                    value={product.count}
                                    InputProps={{
                                        endAdornment: <InputAdornment position="start">шт</InputAdornment>,
                                    }}
                                    onChange={(e) => dispatch(CartSet(
                                        (() => {
                                            let result = { ...product, count: e.target.value }
                                            return result
                                        })
                                            ()))}
                                >

                                </TextField>
                                <Button variant="outlined" size="small" onClick={() => dispatch(CartIncOne(product))}>-</Button>
                                <Button variant="outlined" size="small" onClick={() => dispatch(CartDel(product))}>удалить</Button>
                            </Box>
                            <Divider />
                        </div>
                    )
                    ) */}

    return (
        <Drawer
            anchor="right"
            open={cartOpen}
            onClose={closeCart}
            sx={{position: "relative" }}

        >
            <List sx={{

                display: "flex",
                justifyContent: "space-between",
                position: "fixed",
                backgroundColor: "white",
                zIndex: 1,
            }}>
                <ListItem >
                    <ListItemIcon sx={{ minWidth: "30px" }}>
                        <ShoppingBasket />
                    </ListItemIcon>
                    <ListItemText primary="Корзина" />
                </ListItem>
                <ListItem>
                <Button sx={{ mr: 1 }}  variant="outlined" onClick={() => dispatch(CartClear())}>Очитить корзину</Button>
                    {userAuth ? 
                    <Button variant="outlined" onClick={() => dispatch(actionOrderUpsert(cartStateForOrderUpsert))}>Оформить заказ</Button> :
                    <Button disabled variant="outlined" >Оформить заказ</Button>
                    }                    
                </ListItem>

            </List>
            
            <Divider />

            <List sx={{ mt: "80px",  minWidth: "350px",
                maxWidth: "600px"  }}>
                {!userAuth && <Typography mt={'10px'} ml={1} color={"red"}>Для оформления заказа необходимa <Link to='/login'>авторизация</Link></Typography>}
                {cartState.length ?
                    cartState.map(productsRender) : <ListItem>Ваша корзина пока пуста! </ListItem>
                }
            </List>

        </Drawer>
    )
}

export default Basket