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';
import defaultImage from "../../assets/images/default.png"

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,
    minDiscountPrice,
    minDiscountPriceCurrency,
    maxDiscountPrice,
    maxDiscountPriceCurrency,
    extra_desc,
    selected = false
  ) => {

    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: 10,
                  lg: 20
                },
                left: {
                  xs: 0,
                  sm: 0,
                  md: 10,
                  lg: 20
                },
                boxShadow: 0,
                fontSize: 10
              }}
              variant="contained"
            >
              NEW
            </Button>

            <Box sx={{ pb: 1, pt: 1, width: "90%" }}>
              <Typography variant="body2" sx={{
                fontWeight: "100", fontSize: {
                  xs: "0.65rem",
                  sm: "0.65rem",
                  md: "0.75rem",
                },
              }}>
                {collection_name}
              </Typography>
              <Typography variant="body2" sx={{
                fontWeight: "400", fontSize: {
                  xs: "0.73rem",
                  sm: "0.73rem",
                  md: "0.875rem",
                },
              }}>
                {title}
              </Typography>
              <Typography
                variant="body2"
                sx={{
                  fontWeight: "100",
                  fontSize: {
                    xs: "0.73rem",
                    sm: "0.73rem",
                    md: "0.875rem",
                  },
                  textDecoration: (minDiscountPrice > 0) ? "line-through" : "none"
                }}
              >
                {`${minPriceCurrency} ${parseFloat(minPrice).toFixed(2)}`}
              </Typography>

              {(minDiscountPrice > 0) && <Typography
                variant="body2"
                sx={{
                  fontWeight: "100",
                  fontSize: {
                    xs: "0.73rem",
                    sm: "0.73rem",
                    md: "0.875rem",
                  },
                }}
              >
                {`${minDiscountPriceCurrency} ${parseFloat(minDiscountPrice).toFixed(2)}`}
              </Typography>}
            </Box>
          </Box>
        </a>
      </Grid>
    )

  }


  return (
    <Box sx={{
      my: {
        xs: 0,
        sm: 2,
        md: 5
      }
    }}>

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

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

      <Box sx={{ mt: 2 }}>
        <Swiper
          modules={[Scrollbar, A11y]}
          spaceBetween={10}
          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,
              compareAtPriceRangeMinVariantPrice,
              compareAtPriceRangeMaxVariantPrice,
              productType,
              variants,
              selected,
            } = product;

            let minPrice = minVariantPrice.amount
            let minPriceCurrency = minVariantPrice.currencyCode
            let maxPrice = maxVariantPrice.amount
            let maxPriceCurrency = maxVariantPrice.currencyCode
            // SHOULD BE THE DISCOUNTED PRICE
            let minDiscountPrice = compareAtPriceRangeMinVariantPrice.amount;
            let minDiscountPriceCurrency = compareAtPriceRangeMinVariantPrice.currencyCode;
            let maxDiscountPrice = compareAtPriceRangeMaxVariantPrice.amount;
            let maxDiscountPriceCurrency = compareAtPriceRangeMaxVariantPrice.currencyCode;

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

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

          })}

        </Swiper>
      </Box>

    </Box>
  );
};

export default ProductSelected;
