import { useEffect, useState } from 'react';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Autoplay, Pagination } from 'swiper/modules';
import 'swiper/css';
import 'swiper/css/pagination';
import { IMAGE_ROOT } from '@/shared/constants/common';
import { useHomeBannerListMutation } from '../api/use-home-banner-list-mutation';
import { 
  BannerList,
  BannerType,
  HomeBannerListParams,
  HomeBannerListResponse
} from '../model/types';

export const HomeBannerList = () => {

  const { mutateAsync: homeBannerList } = useHomeBannerListMutation();

  const [bannerList, setBannerList] = useState<Array<BannerList>>([]);

  const callHomeBannerList = () => {
    let params: HomeBannerListParams = {
      bannerType: BannerType.MAIN
    };

    homeBannerList(params).then((rs: HomeBannerListResponse) => {
      console.log(rs);
      if(rs.bannerList && rs.bannerList.length > 0){
        setBannerList(rs.bannerList);
      }
      else{
        setBannerList([]);
      }
    }).finally(() => {
      /*
      let items = [
        {title: '배너 이미지1', imageUrl: IMAGE_ROOT + '/sample_banner_0.png',  linkUrl: 'http://www.google.com', order: 3},
        {title: '배너 이미지2', imageUrl: IMAGE_ROOT + '/home-banner01.png', linkUrl: 'http://www.naver.com', order: 1},
        {title: '배너 이미지3', imageUrl: IMAGE_ROOT + '/home-banner01.png', linkUrl: 'http://www.daum.net', order: 2},
      ];
      // sort 추가 한다
      items.sort((a, b) => a.order - b.order);
      setBannerList(items);
      */
    });
  };

  useEffect(() => {
    callHomeBannerList();
  }, []);

  const onClickToMove = (linkUrl?: string) => {
    if(!!linkUrl){
      window.open(linkUrl);
    }
  };

  const swiperPagination = {
    bulletClass: 'banner-dot',
    bulletActiveClass: 'active',
    el: '.banner-pagination'
  };

  return (
    <>
      { bannerList && bannerList.length > 0 &&
        <div className="swiper-banner">
          <div className="banner-wrapper">
            <Swiper
              modules={[Pagination, Autoplay]}
              slidesPerView={1}
              pagination={ swiperPagination }
            >
            {
              bannerList.map((value, index) => (
                <SwiperSlide
                  key={ `banner-swiper-key-${index}` }
                >
                  <img 
                    src={ value.imageUrl } 
                    alt={ value.title }
                    style={{ 
                      objectFit: 'contain',
                      width: '100%',
                      height: '100%'
                    }}
                    onClick={ () => onClickToMove(value.linkUrl) }
                  />
                </SwiperSlide>
              ))
            }
            </Swiper>
          </div>
          <div className="banner-pagination"></div>
        </div> 
      }
    </>
  );
};