// 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 { useEffect, useMemo, useState } 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 [data, setData] = useState(null);
  useEffect(() => {
    const fetchData = async () => {
      const res = await fetch(`/api/hero-banner?type=index-a-1`);
      const { data } = await res.json();
      if (data) {
        setData(data);
      }
    };

    fetchData();
  }, []);
  const heroBanner = data;

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

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

  const customLoader = ({ src }) => {
    return src; // Loader yang mengembalikan URL gambar asli
  };

  const BannerComponent = useMemo(() => {
    if (!heroBanner) return null;

    return heroBanner.map((banner, index) => (
      <SwiperSlide key={index}>
        <Link href={banner.url} className='w-full h-auto'>
          <Image
            loader={customLoader}
            src={banner.image}
            alt={banner.name}
            width={1152}
            height={768}
            className='w-full h-auto'
            priority={index === 0}
            loading={index === 0 ? 'eager' : 'lazy'}
            placeholder='blur'
            blurDataURL='/images/indoteknik-placeholder.png'
            sizes='(max-width: 768px) 100vw, 50vw'
          />
        </Link>
      </SwiperSlide>
    ));
  }, [heroBanner]);

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

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

export default HeroBanner;
