import { useEffect, useState } from 'react'
import { Box, Button, IconButton } from '@mui/material'
import SocialMedia from '../components/SocialMedia'
import Feature from '../components/Feature'
import Grid from '@mui/material/Grid2';
import Typography from '@mui/material/Typography';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import AddIcon from '@mui/icons-material/Add';
import RemoveIcon from '@mui/icons-material/Remove';
import { addItemToCart, updateItemQuantity } from '../redux/slices/cartSlice';
import { useSelector, useDispatch } from 'react-redux';


// Utility function to check if an object is empty
const isEmptyObject = (obj) => Object.keys(obj).length === 0 && obj.constructor === Object;

const Cart = () => {

  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(() => {

    console.log(cart)

  }, [])

  useEffect(() => {

    if(cart?.lines?.nodes?.length == 0) window.location.href = "/"

    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 (
    <>
      <Box sx={{
        px: {
          xs: 2,
          md: 5,
          lg: 5
        },
        mb: {
          xs: 0,
          md: 5,
          lg: 10
        },
        mt: 10
      }}>


        {/* Header */}
        <Grid container spacing={2} alignItems="center" sx={{ mb: 5, flexDirection: { xs: 'column-reverse', lg: 'row' } }}>

          <Grid item size={{ xs: 12, md: 4 }}>
            <Typography variant="h5" sx={{ fontWeight: "bold" }}>
              SHOPPING BAG
            </Typography>
          </Grid>

        </Grid>

        {/* Product List */}
        <TableContainer>
          <Table sx={{ minWidth: 650, borderTop: "1px solid rgba(0,0,0,0.4)", borderBottom: "1px solid rgba(0,0,0,0.4)", mb: 5 }}>
            <TableHead>
              <TableRow>
                <TableCell width={150}>
                  <Typography variant='body1'>Item</Typography>
                </TableCell>
                <TableCell>
                  <Typography variant='body1'>Description</Typography>
                </TableCell>
                <TableCell align='center'>
                  <Typography variant='body1'>Variant</Typography>
                </TableCell>
                <TableCell align='center'>
                  <Typography variant='body1'>Quantity</Typography>
                </TableCell>
                <TableCell align='center'>
                  <Typography variant='body1'>Unit Price</Typography>
                </TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {cartProducts?.map(({ id, cost, merchandise, quantity }) => {

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

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

                return (
                  <TableRow
                    key={id}
                    sx={{
                      '& td, & th': { border: 0 },
                      '&:last-child td, &:last-child th': { border: 0 }
                    }}
                  >
                    <TableCell component="th" scope="row">
                      <img
                        src={image.src}
                        alt={image.src}
                        style={{
                          width: 100,
                          height: 100,
                          aspectRatio: '4 / 4',
                          objectFit: 'cover',
                          objectPosition: "top center",
                        }}
                      />
                    </TableCell>

                    <TableCell>
                      <Typography variant='body2' sx={{ fontWeight: "bold", mb: 1 }}>{(product.title == "Default Title") ? "" : product.title} </Typography>

                      {product?.collections?.nodes?.map(({ title }) => (<Typography variant='body2'>{ (title == "Default Title") ? "" : title}</Typography>))}

                    </TableCell>

                    <TableCell align='center'>
                      <Typography variant='body2' sx={{ fontWeight: "bold" }} >{ (title == "Default Title") ? "" : title}</Typography>
                    </TableCell>

                    <TableCell align='center'>
                      <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>
                    </TableCell>

                    <TableCell align='center'>
                      <Typography variant='h6' sx={{ fontWeight: "bold" }}>{`${currencyCode} ${parseFloat(amount).toFixed(2)}`}</Typography>
                    </TableCell>
                    
                  </TableRow>
                )

              })}
            </TableBody>
          </Table>
        </TableContainer>

        {/* INVOICES */}
        <Grid container spacing={2} sx={{ mb: 5 }}>

          <Grid item size={{ xs: 12, sm: 4, md: 3 }} sx={{ ml: "auto" }}>
            <Box
              display="flex"
              justifyContent="space-between"
              alignItems="center"
              sx={{ mb: 2 }}
            >
              <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"
              sx={{ mb: 2 }}
            >
              <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"
              sx={{ mb: 2 }}
            >
              <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>

        {/* BUY NOW */}
        <Box sx={{ mb: 15 }}>
          <Box sx={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexDirection: { xs: "column-reverse", md: "row" } }}>
            <Typography variant='body2'><span style={{ fontWeight: "bolder" }}>NEED HELP?</span> CALL US: +60 17 228 2072 | EMAIL CUSTOMER CARE | SHIPPING INFORMATION | RETURNS & EXCHANGES</Typography>
            <Button
              variant="contained"
              color="common.black"
              onClick={() => { window.location.href = cart.checkoutUrl }}
              sx={{
                backgroundColor: (theme) => theme.palette.common.black,
                color: "white",
                textTransform: "none",
                px: 8,
                py: 2,
                mb: {
                  xs: 5,
                  md: 0
                },
                "&:hover": {
                  backgroundColor: (theme) => theme.palette.grey[900],
                },
              }}>BUY NOW</Button>
          </Box>
        </Box>

        <SocialMedia />
        <Feature />
      </Box>
    </>
  )
}

export default Cart