import React, { useMemo } from "react";
import Link from "next/link";
import { useQuery } from "react-query";
import Image from "~/components/ui/image";
import { getBanner } from "~/services/banner";
import { getRandomInt } from '@/utils/getRandomInt';

const SideBanner = () => {
  const fetchSideBanner = useQuery({
    queryKey: 'sideBanner',
    queryFn: () => getBanner({ type: 'side-banner-search' })
  });
  // ubah dari static menjadid dynamic dengan menggunakan random index
  const length = useMemo(() => fetchSideBanner.data?.length, [fetchSideBanner.data]);
  const randomIndex = useMemo(() => getRandomInt(length), [length]);
  const banner = fetchSideBanner?.data?.[randomIndex] || false;

  return banner && (
    <>
      {banner.url ? (
        <Link href={banner.url}>
          <Image src={banner.image} alt={banner.name} width={315} height={450} className='object-cover object-center rounded-lg' />
        </Link>
      ) : (
        <Image src={banner.image} alt={banner.name} width={315} height={450} className='object-cover object-center rounded-lg' />
      )}
    </>
  );
}
export default SideBanner;
