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

const FooterBanner = () => {
  const fetchFooterBanner = useQuery({
    queryKey: 'footerBanner',
    queryFn: () => getBanner({ type: 'bottom-search-promotion' })
  })

  const length = useMemo(() => fetchFooterBanner.data?.length, [fetchFooterBanner.data]);
  const randomIndex = useMemo(() => getRandomInt(length), [length]);
  const banner = fetchFooterBanner?.data?.[randomIndex] || false;

  return banner && (
    <>
      {banner.url && (
        <Link href={banner.url}>
          <Image src={banner.image} alt={banner.name} width={924} height={150} className='object-cover object-center rounded-lg' />
        </Link>
      )}

      {!banner.url && (
        <Image src={banner.image} alt={banner.name} width={924} height={150} className='object-cover object-center rounded-lg' />
      )}
    </>
  )
}
export default FooterBanner