// Swiper
import { Autoplay, Pagination } from 'swiper';
import 'swiper/css';
import 'swiper/css/autoplay';
import 'swiper/css/pagination';
import { Swiper, SwiperSlide } from 'swiper/react';

import Image from 'next/image';
import { useMemo } from 'react';
import { useQuery } from 'react-query';

import { bannerApi } from '@/api/bannerApi';
import Link from '@/core/components/elements/Link/Link';
import DesktopView from '@/core/components/views/DesktopView';
import MobileView from '@/core/components/views/MobileView';
import SmoothRender from '~/components/ui/smooth-render';

const swiperBanner = {
  autoplay: {
    delay: 6000,
    disableOnInteraction: false,
  },
  modules: [Pagination, Autoplay],
  loop: true,
  className: 'border border-gray_r-6 min-h-full',
  slidesPerView: 1,
};

const HeroBanner = () => {
  const heroBanner = useQuery('heroBanner', bannerApi({ type: 'index-a-1' }));

  const swiperBannerMobile = {
    ...swiperBanner,
    pagination: { dynamicBullets: true, clickable: true },
  };

  const swiperBannerDesktop = {
    ...swiperBanner,
    pagination: { dynamicBullets: false, clickable: true },
  };

  const BannerComponent = useMemo(() => {
    return heroBanner.data?.map((banner, index) => (
      <SwiperSlide key={index}>
        <Link href={banner.url} className='w-full h-auto'>
          <Image
            src={banner.image}
            alt={banner.name}
            width={1152}
            height={768}
            className='w-full h-auto'
          />
        </Link>
      </SwiperSlide>
    ));
  }, [heroBanner.data]);

  return (
    <>
      <MobileView>
        <SmoothRender
          isLoaded={heroBanner.data?.length > 0}
          height='68vw'
          duration='750ms'
          delay='100ms'
        >
          <Swiper {...swiperBannerMobile}>{BannerComponent}</Swiper>
        </SmoothRender>
      </MobileView>

      <DesktopView>
        {heroBanner.data?.length > 0 && (
          <Swiper {...swiperBannerDesktop}>{BannerComponent}</Swiper>
        )}
      </DesktopView>
    </>
  );
};

export default HeroBanner;
