import * as React from "react"
import SwiperCore, { Navigation, Pagination } from "swiper"
import { Swiper, SwiperSlide } from "swiper/react"
import { Container, Icon } from "@/components"
import * as styles from "./index.module.scss"

SwiperCore.use([Navigation, Pagination])

interface IProps<T> {
  className?: string
  smallSwiper?: boolean
  listData: T[]
  children: (item: T) => React.ReactNode
  colNum?: number
  id?: string
}

const randomId = () => {
  const charSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZqwertyuiopasdfghjklzxcvbnm".split(
    ""
  )
  let id = ""
  for (let i = 0; i < 7; i++) {
    const pos = Math.floor(Math.random() * charSet.length)
    id += charSet[pos]
  }
  return id
}

const SwiperContainer: <T>(props: IProps<T>) => React.ReactElement = ({
  className,
  smallSwiper,
  listData,
  children,
  colNum,
  id,
}) => {
  const swiperId = id ?? randomId()
  const SwiperAttrs = {
    navigation: {
      nextEl: `#${swiperId}-next`,
      prevEl: `#${swiperId}-prev`,
    },
    pagination: {
      clickable: true,
    },
    breakpoints: {
      320: {
        slidesPerView: 1,
        slidesPerGroup: 1,
      },
      768: {
        slidesPerView: 2,
        slidesPerGroup: 2,
      },
      1024: {
        slidesPerView: smallSwiper ? 2 : 3,
        slidesPerGroup: smallSwiper ? 2 : 3,
      },
    },
  }

  if (colNum) {
    SwiperAttrs.breakpoints["1024"] = {
      slidesPerView: colNum,
      slidesPerGroup: colNum,
    }
  }

  return (
    <section
      className={`${styles.swiperContainer} ${className ?? ""} ${
        smallSwiper ? styles.smallSwiper : ""
      }`}
    >
      <Container>
        <div className={smallSwiper ? "common-center-container" : ""}>
          <div className={styles.listContent}>
            <Swiper {...SwiperAttrs} className={styles.swiper}>
              {listData &&
                listData.length > 0 &&
                listData.map((item, index) => (
                  <SwiperSlide key={index}>
                    <div className={styles.listLoop} key={index}>
                      {children(item)}
                    </div>
                  </SwiperSlide>
                ))}
            </Swiper>
            <div
              className="swiper-button-prev swiper-button-prev-out"
              id={`${swiperId}-prev`}
            >
              <Icon name="chevron-right" />
            </div>
            <div
              className="swiper-button-next swiper-button-next-out"
              id={`${swiperId}-next`}
            >
              <Icon name="chevron-right" />
            </div>
          </div>
        </div>
      </Container>
    </section>
  )
}

export default SwiperContainer
