import React, { memo, useCallback, useEffect } from "react";

import { useDispatch } from "react-redux";

import { updatePanel } from "../../../../actions/panelActions";
import TItemCard, { TYPES } from "../../../../components/TItemCard/TItemCard";
import TVirtualGridList from "../../../../components/TVirtualGridList/TVirtualGridList";
import useScrollTo from "../../../../hooks/useScrollTo";
import { panel_names } from "../../../../utils/Config";
import css from "./RoomThemeList.module.less";

const RoomThemeList = ({ otherRoomThemeInfos, setSelectedThemeExpsOrd }) => {
  const dispatch = useDispatch();
  const { getScrollTo, scrollTop } = useScrollTo();

  useEffect(() => scrollTop({ animate: false }), [otherRoomThemeInfos]);

  const handleClick = useCallback(
    (themeExpsOrd, themeId, themeNm) => () => {
      if (setSelectedThemeExpsOrd) setSelectedThemeExpsOrd(themeExpsOrd);

      dispatch(
        updatePanel({
          name: panel_names.IMAGE_PANEL,
          panelInfo: {
            themeId,
            themeExpsOrd,
            themeNm,
            y: 0,
          },
        })
      );
    },
    [setSelectedThemeExpsOrd]
  );

  const renderItem = useCallback(
    ({ index, ...rest }) => {
      const { themeExpsOrd, themeId, themeImgUrl, themeNm } =
        otherRoomThemeInfos[index];

      return (
        <TItemCard
          className={css.tItemCard}
          imageAlt={themeNm}
          imageSource={themeImgUrl}
          onClick={handleClick(themeExpsOrd, themeId, themeNm)}
          productId={themeId}
          productName={themeNm}
          type={TYPES.horizontal}
          {...rest}
        />
      );
    },
    [handleClick, otherRoomThemeInfos]
  );

  return (
    <div className={css.container}>
      {otherRoomThemeInfos && (
        <TVirtualGridList
          cbScrollTo={getScrollTo}
          className={css.TVirtualGridList}
          dataSize={otherRoomThemeInfos.length}
          itemHeight={165}
          itemWidth={540}
          spacing={12}
          renderItem={renderItem}
        />
      )}
    </div>
  );
};

export default memo(RoomThemeList);
