import Link from '@/core/components/elements/Link/Link';
import Image from 'next/image';
import { useEffect, useState } from 'react';
import { bannerApi } from '../../../api/bannerApi';

const { useQuery } = require('react-query');
const { default: bannerSectionApi } = require('../api/bannerSectionApi');

const BannerSection = () => {
  const [data, setData] = useState(null);
  const [shouldFetch, setShouldFetch] = useState(false);

  useEffect(() => {
    const localData = localStorage.getItem('Homepage_bannerSection');
    if (localData) {
      setData(JSON.parse(localData));
    }else{
      setShouldFetch(true);
    }
  }, []);

  // const fetchBannerSection = async () => await bannerSectionApi();
  const getBannerSection = useQuery('bannerSection', bannerApi({ type: 'home-banner' }), {
    enabled: shouldFetch,
    onSuccess: (data) => {
      if (data) {
        localStorage.setItem('Homepage_bannerSection', JSON.stringify(data));
        setData(data);
      }
    },
  });

  const bannerSection = data;

  return (
    bannerSection &&
    bannerSection?.length > 0 && (
      <div className='grid grid-cols-1 sm:grid-cols-2 gap-4'>
        {bannerSection?.map((banner) => (
          <Link key={banner.id} href={banner.url}>
            <Image
              width={1024}
              height={512}
              quality={85}
              src={banner.image}
              alt={banner.name}
              className='h-auto w-full rounded'
            />
          </Link>
        ))}
      </div>
    )
  );
};

export default BannerSection;
