import React from 'react';
import get from 'lodash/get';
import CapImage from '@capillarytech/cap-ui-library/CapImage';
import CapButton from '@capillarytech/cap-ui-library/CapButton';
import CapColumn from '@capillarytech/cap-ui-library/CapColumn';

export const groupLineStickers = (lineStickers) => {
  const stickerGroup = {};
  // Return early if lineStickers is null or undefined
  if (!lineStickers) return stickerGroup;

  // Now we can safely iterate as lineStickers is defined
  Object?.keys(lineStickers)?.forEach((key) => {
    const category = lineStickers[key];
    if (Array.isArray(category)) {
      //iterating over each category [standard, custom, extended]
      category?.forEach((lineSticker) => {
        const packageId = get(lineSticker, 'definition.packageId');
        if (packageId) {
          const stickerGroupPackageId = stickerGroup[packageId];
          if (stickerGroupPackageId && Array.isArray(stickerGroupPackageId)) {
            stickerGroup[packageId].push(lineSticker);
          } else {
            //initialising with first sticker for each package ID
            stickerGroup[packageId] = [lineSticker];
          }
        }
      });
    }
  });
  return stickerGroup;
}

export const getContent = ({ lineStickers, onStickerSelect }) => (
  <>
    {
      lineStickers.map(({
        _id,
        definition = {},
      }) => (
          <CapColumn span={6} key={_id}>
            <CapButton
              type="flat"
              style={{ padding: 0, margin: 10, height: 'auto' }}
              onClick={() => onStickerSelect(definition)}
            >
              <CapImage
                src={definition.stickerUrl}
                rest = {{ height: 70 }}
                rest={{
                  height: 70,
                  onMouseOut: e => (e.currentTarget.src = definition.stickerUrl),
                  onMouseOver: e => (e.currentTarget.src = definition.animatedStickerUrl || definition.stickerUrl)
                }}
              />
            </CapButton>
          </CapColumn>
        ))
    }
  </>
);

export const getTabPanes = ({ lineStickers, onStickerSelect }) => {
  const groupedStickers = groupLineStickers(lineStickers);
  const tableKeys = Object.keys(groupedStickers);
  return tableKeys.map((packageId) => {
    const stickerUrl = get(groupedStickers[packageId], '[0].definition.stickerUrl', '');
    return {
      key: packageId,
      tab: (
        <CapImage
            src={stickerUrl}
            rest={{ height: 33 }}
        />
      ),
      content: getContent({ lineStickers: groupedStickers[packageId], onStickerSelect }),
    }
  });
};