import { useEffect, useState } from "react";
import { Drawer, Box, Typography, IconButton, Button } 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%",
          },
          height: "97%",
          padding: 2,
        },
      }}
    >
      <Box sx={{ display: "flex", flexDirection: "column", height: "100%" }}>
        {/* Header */}
        <Box
          sx={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            marginBottom: 2,
          }}
        >
          <Typography variant="h6">Your Cart</Typography>
          <IconButton onClick={onClose}>
            <CloseIcon />
          </IconButton>
        </Box>

        <Box sx={{ flexGrow: 1 }}>
          {/* 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={2}>
                        <Box
                          component="img"
                          src={merchandise?.image?.src}
                          alt={product.name}
                          sx={{
                            width: "100%",
                            height: "auto",
                            borderRadius: 2,
                          }}
                        />
                      </Grid>

                      {/* Product Details */}
                      <Grid item size={10} sx={{ paddingLeft: 1 }}>
                        <Typography variant="body2" sx={{
                          fontWeight: "400", fontSize: {
                            xs: "0.875rem",
                            sm: "0.875rem",
                            md: "1.1rem",
                          }
                        }}>
                          {product?.title}
                        </Typography>
                        
                        {(title != "Default Title") && 
                        <Typography variant="body2" sx={{
                          fontWeight: "100", fontSize: {
                            xs: "0.875rem",
                            sm: "0.875rem",
                            md: "1.1rem",
                          }
                        }}>{`VARIANT: ${title}`}</Typography>}

                        <Box sx={{ display: "flex", alignItems: "center" }}>

                          <Typography variant="body2" sx={{
                            fontWeight: "100", fontSize: {
                              xs: "0.875rem",
                              sm: "0.875rem",
                              md: "1.1rem",
                            }
                          }}>{`${currencyCode} ${parseFloat(amount).toFixed(2)}`}</Typography>

                          <Box sx={{ display: "flex", ml: "auto" }}>
                            <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>

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

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

        <Box sx={{ mt: "auto", display:(cartProducts.length > 0) ? "block" : "none" }}>
          {/* INVOICES */}
          <Grid container spacing={2}>

            <Grid item size={12}>
              <Box
                display="flex"
                justifyContent="space-between"
                alignItems="center"
              >
                <Typography variant="body1" sx={{ fontWeight: "400" }}>Subtotal</Typography>
                <Typography variant="body1" sx={{ fontWeight: "400" }}>
                  {`
                    ${cart?.cost?.subtotalAmount?.currencyCode} 
                    ${parseFloat(cart?.cost?.subtotalAmount?.amount).toFixed(2)}
                  `}
                </Typography>
              </Box>
              <Box
                display="flex"
                justifyContent="space-between"
                alignItems="center"
              >
                <Typography variant="body1" sx={{ fontWeight: "400" }}>Taxes</Typography>
                <Typography variant="body1" sx={{ fontWeight: "400" }}>
                  {`
                    ${cart?.cost?.totalTaxAmount?.currencyCode || ""} 
                    ${parseFloat(cart?.cost?.totalTaxAmount?.amount || 0).toFixed(2)}
                  `}
                </Typography>
              </Box>
              <Box
                display="flex"
                justifyContent="space-between"
                alignItems="center"
              >
                <Typography variant="body1" sx={{ fontWeight: "400" }}>Total</Typography>
                <Typography variant="body1" sx={{ fontWeight: "bold" }}>
                  {`
                    ${cart?.cost?.totalAmount?.currencyCode} 
                    ${parseFloat(cart?.cost?.totalAmount?.amount).toFixed(2)}
                  `}
                </Typography>
              </Box>
            </Grid>
            <Grid item size={12} sx={{ textAlign: "center" }}>
              <Button
                variant="contained"
                color="primary"
                onClick={() => {
                  window.location.href = '/cart'
                }}>
                CHECKOUT NOW
              </Button>
            </Grid>
          </Grid>
        </Box>

      </Box>
    </Drawer>
  );
};

export default SideCart;
