import React, { useEffect, useState } from 'react';
import classNames from 'classnames/bind';

import Flicking, { ViewportSlot } from '@egjs/react-flicking';
import { Arrow } from '@egjs/flicking-plugins';
import styles from './CollectionScrollList.scss';
import CollectionCard from '@src/components/common/CollectionCard';
import { ICollection } from 'metarare';

const cx = classNames.bind(styles);

interface IOwnProps {
  list?: ICollection[];
};

const PANEL_COUNT = 6;

const CollectionScrollList: React.FC<IOwnProps> = ({
  list
}) => {
  const plugins = [new Arrow()];
  const [panel, setPanel] = useState<ICollection[][]>([]);

  useEffect(() => {
    if (list?.length) {
      const panel = [];
      for (let i = 0; i < list.length; i += PANEL_COUNT) {
        panel.push(list.slice(i, i + PANEL_COUNT));
      }

      setPanel(panel);
    }
  }, [list]);

  return (
    <div className={cx('collection_scroll')}>
      {!!panel.length && (
        <Flicking plugins={plugins}>
          {panel.map((list, index) => (
            <div className={cx('collection_panel')} key={index}>
              {list.map((item, index) => (
                <CollectionCard
                  key={`${item.id}_${index}`}
                  thumbSrc={item.thumbnail_image}
                  name={item.name}
                  author={item.user_name}
                  isOfficial={item.is_official}
                  totalItem={item.items}
                  totalVolume={item.total_volume}
                  className={'scroll'}
                  coverImage={item.cover_image}
                />
              ))}
            </div>
          ))}
          <ViewportSlot>
            <span className={cx('flicking-arrow-prev', 'btn_flicking', 'main_prev')}></span>
            <span className={cx('flicking-arrow-next', 'btn_flicking', 'main_next')}></span>
          </ViewportSlot>
        </Flicking>
      )}
    </div>
  );
};

export default CollectionScrollList;
