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

      let selectedProducts = products.filter(({ selected }) => selected) || []
      
      //sort
      selectedProducts = selectedProducts.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
      setFilterProducts(selectedProducts)

    }

  }, [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 = (handle, img_url, title, collection_name, minPrice, minPriceCurrency, maxPrice, maxPriceCurrency, extra_desc) => {

    return (
      <Grid item size={{ xs: 6, sm: 6, md: 3 }}>
        <a
          href={`/products/${handle}`}
          style={{
            color: 'black',
            textDecoration: 'none'
          }}>
          <Box
            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:{
                xs:0,
                sm:0,
                md:20
              }, 
              left: {
                xs:0,
                sm:0,
                md:20
              }, 
              boxShadow: 0,
              fontSize:10
            }} variant="contained">
              NEW
            </Button>

            <Box sx={{ pt: 3 }}>
              <Typography variant="body1" sx={{ fontWeight: "400", mb: 1 }}>
                {collection_name}
              </Typography>
              <Typography variant="h6" 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>
        </a>
      </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 { handle, 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

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

        })}

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

export default ProductSelected;
