import { useEffect, useState, useRef } from 'react';
import { Box, Typography, Button, useMediaQuery } from '@mui/material';
import Grid from '@mui/material/Grid2';
import { useSelector, useDispatch } from 'react-redux';
import { fetchProducts } from '../../redux/slices/productSlice';

import { Swiper, SwiperSlide } from 'swiper/react';
import { Scrollbar, A11y } from 'swiper/modules';

import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';
import KeyboardArrowRightIcon from '@mui/icons-material/KeyboardArrowRight';

const ProductSelected = () => {

  const swiperRef = useRef(null); // Create a ref for the Swiper instance
  const products = useSelector((state) => state.products.products.data)

  const [filterProducts, setFilterProducts] = useState([])

  useEffect(() => {

    if (products.length > 0) {
      setFilterProducts(products.filter(({ selected }) => selected))
    }

  }, [products])

  const swipeToLeft = () => {
    if (swiperRef.current) {
      swiperRef.current.slidePrev(); // Move to the previous slide
    }
  };

  const swipeToRight = () => {
    if (swiperRef.current) {
      swiperRef.current.slideNext(); // Move to the previous slide
    }
  };


  const renderProduct = (id, img_url, title, collection_name, minPrice, minPriceCurrency, maxPrice, maxPriceCurrency, extra_desc) => {

    return (
      <Grid item size={{ xs: 6, sm: 6, md: 3 }}>

        <Box
          onClick={() => { window.location.href = `/products/${id}` }}
          sx={{
            overflow: 'hidden',
            position: 'relative',
            cursor: 'pointer'
          }}

        >
          <img
            src={img_url}
            alt={title}
            style={{
              width: '100%',
              aspectRatio: '3 / 4',
              objectFit: 'cover',
              objectPosition: 'top center'
            }}
          />

          {/* <Button sx={{ position: "absolute", top: 20, left: 20, boxShadow: 0 }} variant="contained">
            NEW
          </Button> */}

          <Box sx={{ pb: 5, pt: 3 }}>
            <Typography variant="body1" sx={{ fontWeight: "400", mb: 1 }}>
              {collection_name}
            </Typography>
            <Typography variant="h5" sx={{ fontWeight: "bolder", mb: 1 }}>
              {title}
            </Typography>
            <Typography variant="body1" sx={{ fontWeight: "400" }}>
              {`${minPriceCurrency} ${parseFloat(minPrice).toFixed(2)}`}
            </Typography>
            <Typography variant="body1" sx={{ mt: 2 }}>
              {extra_desc}
            </Typography>
          </Box>
        </Box>
      </Grid>
    )

  }


  return (
    <Box sx={{
      mb: 5,
    }}>

      {/* OFFSET PURPOSE */}
      <Grid size={{ xs: 12, md: 4 }} sx={{ mx: "auto", display: "flex", alignItems: "center", justifyContent: "center", my: 4 }}>
        <ChevronLeftIcon
          style={{
            cursor:"pointer",
            color:"#B7B7B7"
          }}
          onClick={swipeToLeft}
        />
        <Typography variant="h4" sx={{mx:2}}>
          NEW IN
        </Typography>

        <KeyboardArrowRightIcon
          style={{
            cursor:"pointer",
            color:"#B7B7B7"
          }}
          onClick={swipeToRight}
        />
      </Grid>

      <Swiper
        modules={[Scrollbar, A11y]}
        spaceBetween={20}
        breakpoints={{
          0: { slidesPerView: 2 }, // For very small screens
          640: { slidesPerView: 2 }, // For screens >= 640px
          1024: { slidesPerView: 4 }, // For screens >= 1024px
        }}
        pagination={{ clickable: true }}
        scrollbar={{ draggable: true }}
        onSwiper={(swiper) => (swiperRef.current = swiper)}
      >
        {filterProducts.map((product, index) => {

          let { id, title, images, collections, minVariantPrice, maxVariantPrice, productType, variants } = product

          let minPrice = minVariantPrice.amount
          let minPriceCurrency = minVariantPrice.currencyCode
          let maxPrice = maxVariantPrice.amount
          let maxPriceCurrency = maxVariantPrice.currencyCode

          let img_url = images[0].url
          let collection_name = collections[0].title

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

          return (
            <SwiperSlide>
              {renderProduct(prodID, img_url, title, collection_name, minPrice, minPriceCurrency, maxPrice, maxPriceCurrency, "")}
            </SwiperSlide>
          )

        })}

      </Swiper>
    </Box>
  );
};

export default ProductSelected;
