// ** React Imports
import React, { useContext, useEffect, useState } from 'react';

// ** MUI Imports
import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import { styled } from '@mui/material/styles';
import Typography from '@mui/material/Typography';
import IconButton from '@mui/material/IconButton';
import CardContent from '@mui/material/CardContent';
import CardActions from '@mui/material/CardActions';
import Grid from '@mui/material/Grid';
import AddCircleOutlineIcon from '@mui/icons-material/AddCircleOutline';
import RemoveCircleOutlineIcon from '@mui/icons-material/RemoveCircleOutline';
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';

// ** Icons Imports
import { Stack, TextField } from '@mui/material';
import { CartContext } from 'src/contexts/cart';

// Styled Grid component
const StyledGrid = styled(Grid)(({ theme }) => ({
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  [theme.breakpoints.down('md')]: {
    borderBottom: `1px solid ${theme.palette.divider}`,
  },
  [theme.breakpoints.up('md')]: {
    borderRight: `1px solid ${theme.palette.divider}`,
  },
}));

const CartItemDetail = ({ checking_out, products, pid, qty }) => {
  let [product, setProduct] = useState(null);

  const { addToCart, removeFromCart, total_price, changeCartItemQty } = useContext(CartContext);

  const qtyRef = React.useRef();

  const handleSelectAll = () => {
    qtyRef.current.select();
  };

  useEffect(() => {
    let result = products.filter(p => p.pid === pid);
    console.log({ result, pid, products });
    setProduct(result[0]);
  }, [pid]);

  if (!product) return <>Updating product</>;

  return (
    <Card sx={{ width: '500px' }}>
      <Grid container spacing={6}>
        <StyledGrid item md={5} xs={12}>
          <CardContent sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <div
              style={{
                width: '100%',
                height: '100%',
                minWidth: '100px',
                minHeight: '100px',
                backgroundImage: `url('/api/files/get?dir_prefix=${product.product_image}')`,
                backgroundSize: 'contain',
                backgroundPosition: 'center',
                backgroundRepeat: 'no-repeat',
              }}
            />
          </CardContent>
        </StyledGrid>
        <Grid
          item
          xs={12}
          md={7}
          sx={{
            paddingTop: ['0 !important', '0 !important', '1.5rem !important'],
            paddingLeft: ['1.5rem !important', '1.5rem !important', '0 !important'],
          }}
        >
          <CardContent>
            <Typography variant="h6" sx={{ marginBottom: 2 }}>
              {product.name}
            </Typography>
            <Typography variant="body2" sx={{ marginBottom: 3.5 }}>
              {product.description}
            </Typography>
            <Typography sx={{ fontWeight: 500, marginBottom: 3 }}>
              Price:{' '}
              <Box component="span" sx={{ fontWeight: 'bold' }}>
                ${parseInt(product.price).toFixed(2)}
              </Box>
            </Typography>
          </CardContent>

          <CardActions>
            <Stack direction="row" justifyContent={'flex-end'} style={{ width: '100%' }}>
              <Stack sx={{ display: 'flex', flexDirection: 'row', justifyContent: 'flex-end' }}>
                <Box flexGrow={10} backgroundColor="pink"></Box>
                <IconButton
                  disabled={checking_out}
                  id="long-button"
                  aria-label="share"
                  aria-haspopup="true"
                  onClick={() => addToCart(pid, 1, parseInt(product.price))}
                  aria-controls="long-menu"
                >
                  <AddCircleOutlineIcon fontSize="small" />
                </IconButton>

                <Box textAlign={'center'} width={'2rem'}>
                  <TextField
                    disabled={checking_out}
                    inputRef={qtyRef}
                    variant="standard"
                    value={qty}
                    inputProps={{ style: { textAlign: 'center' } }}
                    onChange={e => {
                      try {
                        let final_qty = parseInt(e.target.value);
                        changeCartItemQty(pid, final_qty, product.price);
                      } catch (error) {
                        console.error("user wasn't entered a number");
                      }
                    }}
                    onBlur={e => {
                      try {
                        let final_qty = parseInt(e.target.value);
                        changeCartItemQty(pid, final_qty, product.price);
                      } catch (error) {
                        console.error("user wasn't entered a number");
                      }
                    }}
                    onClick={handleSelectAll}
                  />
                </Box>

                <IconButton
                  disabled={checking_out}
                  id="long-button"
                  aria-label="share"
                  aria-haspopup="true"
                  onClick={() => removeFromCart(pid)}
                  aria-controls="long-menu"
                >
                  {qty == 1 ? (
                    <>
                      <DeleteOutlineIcon fontSize="small" color={'error'} />
                    </>
                  ) : (
                    <>
                      <RemoveCircleOutlineIcon fontSize="small" />
                    </>
                  )}
                </IconButton>
              </Stack>
            </Stack>
          </CardActions>
        </Grid>
      </Grid>
    </Card>
  );
};

export default CartItemDetail;
