import React from 'react';
import CapIcon from '@capillarytech/cap-ui-library/CapIcon';
import CapTooltip from '@capillarytech/cap-ui-library/CapTooltip';

import { TEXT, IMAGE, IMAGE_MAP, STICKER, IMAGE_CAROUSEL, TEMPLATE, VIDEO } from '../constants';
import LineText from '../Text';
import LineImage from '../Image';
import LineSticker from '../Sticker';
import LineImageMap from '../ImageMap';
import LineImageCarousel from '../ImageCarousel';
import LineVideo from '../Video';
import messages from './messages';

export const getTabContent = ({ item, props }) => {
  switch (item) {
    case TEXT: {
      return <LineText {...props} />;
    }
    case IMAGE: {
      return <LineImage {...props} />;
    }
    case STICKER: {
      return <LineSticker {...props} />;
    }
    case IMAGE_MAP: {
      return <LineImageMap {...props} />;
    }
    case TEMPLATE: {
      return <LineImageCarousel {...props} />;
    }
    case VIDEO: {
      return <LineVideo {...props} />;
    }
  }
};

export const itemIcons = {
  [TEXT]: 'text-message',
  [IMAGE]: 'image-message',
  [STICKER]: 'smiley-message',
  [IMAGE_MAP]: 'rich-message',
  [TEMPLATE]: 'carousel-message',
  [VIDEO]: 'rich-video-message',
};


export const getTabPanes = (props) => {
  const tableKeys = [TEXT, IMAGE, STICKER, IMAGE_MAP, TEMPLATE, VIDEO];
  const tableKeysCreatives = [TEXT, IMAGE, IMAGE_MAP, TEMPLATE, VIDEO];
  return (props.isFullMode ? tableKeysCreatives : tableKeys).map((item) => {
    const isSelected = props.activeKey === item;
    return {
      key: item,
      tab: (
        <CapTooltip
          title={props.formatMessage(messages[`${item}Label`])}
        >
          <CapIcon
            type={isSelected ? `${itemIcons[item]}-filled`: itemIcons[item]}
            size="m"
            style={{ margin: 0 }}
          />
        </CapTooltip>
      ),
      content: getTabContent({ item, props }),
    }
  });
};

export const isUrl = (url) => {
  const res = url.match(/(http(s)?:\/\/)(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
  return res;
};

//Checks if the given text is valid, allowing only alphanumeric characters and whitespace
export const isValidText = (text) => {
  const regex = /^(?:[a-zA-Z0-9\s]*)$/;
  return regex.test(text);
};

// WhatsApp CTA button text validation - whitelist approach
// Allow: all letters and numbers (any language), regular space, and safe symbols
// Safe symbols: @ # & ! ? . : , - + / \ ' " = & ₹ € £ $ ^ ( ) { }
export const isValidWhatsappCtaText = (text) => {
  if (typeof text !== 'string') return false;
  if (!/\S/.test(text)) return false; // disallow whitespace-only
  const regex = /^[\p{L}\p{M}\p{N} @#&!?.:,\-+/\\'"=&₹€£$^(){}]*$/u;
  return regex.test(text);
};
