import { Swiper, SwiperSlide } from 'swiper/react'
import { FreeMode } from 'swiper'
import ProductCard from './ProductCard'
import 'swiper/css'
import Image from '@/core/components/elements/Image/Image'
import Link from '@/core/components/elements/Link/Link'
import { useMemo, useRef } from 'react'
import useDevice from '@/core/hooks/useDevice'
import MobileView from '@/core/components/views/MobileView'
import DesktopView from '@/core/components/views/DesktopView'

const bannerClassName =
  'absolute rounded-r top-0 left-0 h-full w-auto md:w-[20%] idt-transition border border-gray_r-6'

const ProductSlider = ({ products, simpleTitle = false, bannerMode = false }) => {
  const bannerRef = useRef('')

  const changeBannerOpacity = (swiper) => {
    if (!bannerMode) return
    const calculateOpacity = (132 + swiper.translate) / 100
    bannerRef.current.style = `opacity: ${calculateOpacity > 0 ? calculateOpacity : 0}`
  }

  const swiperProps = {
    onSliderMove: changeBannerOpacity,
    onSlideChangeTransitionStart: changeBannerOpacity,
    onSlideChangeTransitionEnd: changeBannerOpacity,
    prefix: 'product',
    modules: [FreeMode],
    freeMode: { enabled: true, sticky: false }
  }

  const swiperContent = useMemo(() => {
    return (
      <>
        {bannerMode && (
          <SwiperSlide>
            <Link href={products.banner.url} className='w-full h-full block'></Link>
          </SwiperSlide>
        )}
        {products?.products?.map((product, index) => (
          <SwiperSlide key={index}>
            <ProductCard product={product} simpleTitle={simpleTitle} />
          </SwiperSlide>
        ))}
      </>
    )
  }, [bannerMode, products, simpleTitle])

  return (
    <>
      {bannerMode && (
        <div ref={bannerRef}>
          <Image
            src={products.banner.image}
            alt={products.banner.name}
            style={{ opacity: 1 }}
            className={bannerClassName}
          />
        </div>
      )}
      <MobileView>
        <Swiper slidesPerView={2.2} spaceBetween={12} {...swiperProps}>
          {swiperContent}
        </Swiper>
      </MobileView>

      <DesktopView>
        <Swiper slidesPerView={5.6} spaceBetween={16} {...swiperProps}>
          {swiperContent}
        </Swiper>
      </DesktopView>
    </>
  )
}

export default ProductSlider
