import { Button } from '@headlessui/react'
import Autoplay from 'embla-carousel-autoplay'
import useEmblaCarousel from 'embla-carousel-react'
import { useFetcher, useRouteLoaderData } from 'react-router'

import type { loader } from '~/routes/_news'

export const Banner = () => {
  const loaderData = useRouteLoaderData<typeof loader>('routes/_news')
  const { adsData } = loaderData || {}
  const [emblaReference] = useEmblaCarousel({ loop: true }, [Autoplay()])
  const fetcher = useFetcher()

  return (
    <div className="">
      <div className="relative">
        <div
          className="embla overflow-hidden"
          ref={emblaReference}
        >
          <div className="embla__container flex">
            {adsData?.map(({ image_url: urlImage, url, id }, index) => (
              <fetcher.Form
                method="POST"
                action={`/actions/log/ads/${id}`}
                key={index}
                className="embla__slide max-h-[100px] min-h-[65px] w-full min-w-0 flex-none"
              >
                <Button
                  className="h-full w-full cursor-pointer py-2"
                  type="submit"
                  onClick={() => window.open(url, '_blank')}
                >
                  <img
                    src={urlImage}
                    alt={id}
                    className="h-[70px] w-[100%] object-contain object-center sm:h-full"
                  />
                </Button>
              </fetcher.Form>
            ))}
          </div>
        </div>
      </div>
    </div>
  )
}
