import { useEffect, useState } from "react";
import { Drawer, Box, Typography, IconButton } from "@mui/material";
import Grid from '@mui/material/Grid2';
import CloseIcon from "@mui/icons-material/Close";
import { updateItemQuantity } from "../../redux/slices/cartSlice";
import AddIcon from '@mui/icons-material/Add';
import RemoveIcon from '@mui/icons-material/Remove';
import { useSelector, useDispatch } from 'react-redux';

const SideCart = ({ open, onClose }) => {

  const dispatch = useDispatch()
  const cart = useSelector((state) => state.cart.cart)
  const [cartProducts, setCartProducts] = useState([]) // this is being used as view only, will not used as a way to manipulate cart in any way

  useEffect(() => {

    setCartProducts(cart?.lines?.nodes || [])

  }, [cart])


  const handleUpdateCart = ({ quantity,  lineId}) => {

    let cartHistory = localStorage.getItem('amber-cart');
    cartHistory = cartHistory ? JSON.parse(cartHistory) : {};

    dispatch(updateItemQuantity({
      cartId:cartHistory.id,
      lineId,
      quantity,
    }))

  }

  return (
    <Drawer
      open={open}
      onClose={onClose}
      anchor="right"
      sx={{
        "& .MuiDrawer-paper": {
          backgroundColor: "white",
          color: "black",
          width: {
            xs: "90%",
            sm: "90%",
            md: "30%",
          },
          padding: 2,
        },
      }}
    >
      <Box>
        {/* Header */}
        <Box
          sx={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            marginBottom: 2,
          }}
        >
          <Typography variant="h6">Your Cart</Typography>
          <IconButton onClick={onClose}>
            <CloseIcon />
          </IconButton>
        </Box>

        {/* Product List */}
        {cartProducts && cartProducts?.length > 0 ? (
          cartProducts.map(({ id, cost, merchandise, quantity }, index) => {

            let { amount, currencyCode } = cost.totalAmount
            let { image, product, title } = merchandise

            // ID
            const parts = product?.id?.split('/');
            let prodID = parts[parts.length - 1];

            return (
              <Box
                key={index}
                sx={{
                  display: "flex",
                  alignItems: "center",
                  padding: 1,
                  borderBottom: "1px solid #eee",
                }}
              >
                <Grid container>
                  {/* Product Image */}
                  <Grid item size={4}>
                    <Box
                      component="img"
                      src={merchandise?.image?.src}
                      alt={product.name}
                      sx={{
                        width: "100%",
                        height: "auto",
                        borderRadius: 2,
                      }}
                    />
                  </Grid>

                  {/* Product Details */}
                  <Grid item size={8} sx={{ paddingLeft: 1 }}>
                    <Typography variant="body1" sx={{lineHeight:1, fontWeight: "bold"}}>
                      {product?.title}
                    </Typography>
                    <Typography variant='body2' sx={{ fontWeight: "bold" }}>{`${currencyCode} ${parseFloat(amount).toFixed(2)}`}</Typography>
                    <Typography variant='body2' sx={{ fontWeight: "bold" }} >{title}</Typography>
                    <Box sx={{ display: "flex", justifyContent: "center" }}>

                        <IconButton onClick={() => {

                          handleUpdateCart({ quantity: quantity - 1, lineId:id })
                        }}>
                          <RemoveIcon sx={{ fontSize: 16, margin: "0 15px" }} />
                        </IconButton>

                        <p style={{ fontSize: 20, fontWeight: "bold" }}>{quantity}</p>

                        <IconButton onClick={() => {

                          handleUpdateCart({ quantity: quantity + 1, lineId:id })
                        }}>
                          <AddIcon sx={{ fontSize: 16, margin: "0 15px" }} />
                        </IconButton>

                      </Box>
                  </Grid>
                </Grid>
              </Box>
            )

          })
        ) : (
          <Typography variant="body2" color="text.secondary">
            Your cart is empty.
          </Typography>
        )}
      </Box>
    </Drawer>
  );
};

export default SideCart;
