import React from 'react';
import { FormattedMessage } from 'react-intl';
import CapLabel from '@capillarytech/cap-ui-library/CapLabel';
import CapIcon from '@capillarytech/cap-ui-library/CapIcon';
import CapImage from '@capillarytech/cap-ui-library/CapImage';
import CapDivider from '@capillarytech/cap-ui-library/CapDivider';
import { get } from 'lodash';
import globalMessages from '../Cap/messages';
import { WHATSAPP } from '../CreativesContainer/constants';
import {
  STATUS_OPTIONS,
  TWILIO_CATEGORY_OPTIONS,
  KARIX_GUPSHUP_CATEGORY_OPTIONS,
  KARIX_GUPSHUP_OLDER_CATEGORY_OPTIONS,
  ICS_CATEGORY_OPTIONS,
  WHATSAPP_STATUSES,
  PHONE_NUMBER,
  NONE,
  CTA,
  WHATSAPP_MEDIA_TYPES,
  HOST_TWILIO,
  SIZE_UNITS,
  QUICK_REPLY,
  HOST_ICS,
} from '../Whatsapp/constants';
import './styles.scss';
import pdfIcon from "../../assets/pdfIcon.svg";
import messages from './messages';
import { getDecodedFileName } from '../../utils/common';

export function bytesConversion(x) {
  // the function accepts bytes and convert in appropriate size following the,
  // l variable, this variable holds the size_unit index and displays the
  // respective size, eg : 5120 bytes gives 5 KB and 5242880 gives 5 MB
  let l = 0;
  let n = parseInt(x, 10) || 0;
  // eslint-disable-next-line no-plusplus
  while (n >= 1024 && ++l) {
    n /= 1024;
  }
  return (`${n.toFixed(n < 10 && l > 0 ? 1 : 0)} ${SIZE_UNITS[l]}`);
}
export const getWhatsappDocPreview = (whatsappDocParams) => {
  const { whatsappDocImg = '', whatsappDocName = '', whatsappDocPages = 0} = whatsappDocParams;
  return (
    <>
      <div className="pdf-img-box">
        <CapImage src={whatsappDocImg} alt="upload-document-src" className="pdf-preview-img" />
      </div>
      <div className="pdf-label">
        <CapImage src={pdfIcon} />
        <div className="pdf-info">
          <div className="pdf-name-div">
            <CapLabel type="label9" className="pdf-name">{getDecodedFileName(whatsappDocName)}</CapLabel>
          </div>
          <CapLabel className="pdf-info-sec">
            {whatsappDocPages} {whatsappDocPages > 1 ? <FormattedMessage {...messages.pages} /> : <FormattedMessage {...messages.page} />}{` · ${bytesConversion(whatsappDocParams?.whatsappDocSize)} · `}
            <FormattedMessage {...messages.pdf} />
          </CapLabel>
        </div>
      </div>
    </>
  );
};

export const getWhatsappContent = (template, isPreview) => {
  const {
    versions: {
      base: {
        content: {
          [WHATSAPP.toLowerCase()]: {
            languages = [{}],
            buttonType = NONE,
            buttons: buttonsData = [],
            mediaType = WHATSAPP_MEDIA_TYPES.TEXT,
            imageUrl = '',
            videoPreviewImg = '',
            whatsappDocParams = {},
            templateId = '',
            whatsappMedia: {
              header = '',
              footer = '',
            } = {},
            carouselData = [],
          } = {},
        } = {},
      } = {},
    } = {},
  } = template;
  //removing $'' which was added for twilio enter handling
  let text = languages[0]?.content || '';
  const validVarRegex = /{{([1-9]|1[0-9])}}/g;
  const unsubscribeRegex = /Click {{([1-9]|1[0-9])}} to unsubscribe/g;
  if (text.match(unsubscribeRegex)?.length > 0) {
    const validVarArr = text.match(validVarRegex) || [];
    //replacing Click {{5}} to unsubscribe with Click {{unsubscribe}} to unsubscribe,
    //for listing preview and cards listing
    text = text.replace(
      `${validVarArr[validVarArr.length - 1]}`,
      '{{unsubscribe}}',
    );
  }
  const mediaParams = {};
  switch (mediaType) {
    case WHATSAPP_MEDIA_TYPES.IMAGE:
      mediaParams.whatsappImageSrc = imageUrl;
      break;
    case WHATSAPP_MEDIA_TYPES.VIDEO:
      mediaParams.whatsappVideoPreviewImg = videoPreviewImg;
      break;
    case WHATSAPP_MEDIA_TYPES.DOCUMENT:
      mediaParams.docPreview = getWhatsappDocPreview(whatsappDocParams);
      break;
    default:
      break;
  }

  const getCarouselData = () => {
    if (isPreview && carouselData?.length) {
      return carouselData.map((carousel) => {
        if (carousel?.mediaType === WHATSAPP_MEDIA_TYPES.IMAGE.toLowerCase()) {
          carousel.imageSrc = carousel?.imageUrl;
        }
        if (carousel?.mediaType === WHATSAPP_MEDIA_TYPES.VIDEO.toLowerCase()) {
          carousel.videoSrc = carousel?.videoUrl;
          carousel.videoPreviewImg = carousel?.videoPreviewImg;
        }
        return carousel;
      });
    }
    return carouselData;
  };

  return {
    templateHeaderPreview: header ? <CapLabel className="whatsapp-template-list-header-preview">{header}</CapLabel> : '',
    templateFooterPreview: footer ? <CapLabel className="whatsapp-template-list-footer-preview">{footer}</CapLabel> : '',
    templateMsg: <CapLabel type={isPreview ? 'label5' : 'label9'}>{text}</CapLabel>,
    charCount: text?.length - 1 + header?.length + footer?.length,
    templateId,
    ...(buttonType === CTA && {
      ctaData: buttonsData
    }),
    ...(buttonType === QUICK_REPLY && {
      quickReplyData: buttonsData
    }),
    ...mediaParams,
    carouselData: getCarouselData(),
    ...(isPreview && carouselData?.length && {
      carouselMediaType: carouselData[0]?.mediaType,
    }),
  };
};

export const getWhatsappCta = (template) => {
  const { buttonType = NONE, buttons = [] } = get(
    template,
    `versions.base.content.whatsapp`,
    {},
  );
  const renderArray = [];
  if (buttonType === 'CTA' && buttons?.length) {
    buttons.forEach((cta) => {
      const { type, text } = cta;
      if (text) {
        renderArray.push(
          <CapLabel
            type="label21"
            style={{ textAlign: 'center', marginTop: '12px' }}
          >
            <CapIcon
              type={type === PHONE_NUMBER ? 'call' : 'launch'}
              size="xs"
              svgProps={{ style: { marginRight: '4px' } }}
            />
            {text}
          </CapLabel>,
        );
      }
    });
  }
  return renderArray;
};

// It will render all the quick reply button in mobile preview and template list
export const getWhatsappQuickReply= (template, templatePreview) => {
  const { buttonType = NONE, buttons = [] } = templatePreview ? template : get(
    template,
    `versions.base.content.whatsapp`,
    {},
  );
  const renderArray = [];
  if (buttonType === QUICK_REPLY && buttons?.length) {
    renderArray.push(<CapDivider className={templatePreview ? "whatsapp-divider" : "whatsapp-list-view-divider"} />);
    buttons?.forEach((quickReply, index) => {
      const { text } = quickReply || {};
      if (text) {
        renderArray.push(
          <CapLabel type="label21" className={templatePreview ? "whatsapp-cta-preview" : "whatsapp-list-quick-reply-preview"}>
            <CapIcon
              type='small-link'
              size="xs"
            />
            {text}
          </CapLabel>
        )
      }
      if (index < buttons?.length -1) {
        renderArray.push(<CapDivider className={templatePreview ? "whatsapp-divider" : "whatsapp-list-view-divider"} />);
      }
    })
  }
  return renderArray;
}

export const getWhatsappCarouselButtonView = (buttons, templatePreview) => {
  const renderArray = [];
  if (buttons?.length) {
    renderArray.push(<CapDivider className={templatePreview ? "whatsapp-divider" : "whatsapp-list-view-divider"} />);
    buttons.forEach((button, index) => {
      const { text, buttonType, type } = button || {};
      const currentButtonType = type || buttonType;
      if (text) {
        renderArray.push(
          <CapLabel
            type="label21"
            className="whatsapp-list-view-text-align"
          >
            <CapIcon
              type={currentButtonType === PHONE_NUMBER ? 'call' : currentButtonType === QUICK_REPLY ? "small-link" : 'launch'}
              size="xs"
              svgProps={{ style: { marginRight: '4px' } }}
            />
            {text}
          </CapLabel>,
        );
      }
      if (index < buttons?.length - 1) {
        renderArray.push(<CapDivider className={templatePreview ? "whatsapp-divider" : "whatsapp-list-view-divider"} />);
      }
    });
  }
  return renderArray;
};

export const getWhatsappAutoFill = (template) => {
  const {category}= get(
    template,
    `versions.base.content.whatsapp`,
    {},
  );
  if (category === 'AUTHENTICATION') {
    return (
      <CapLabel
        type="label21"
        className='whatsapp-autofill-btn'
      >
        <FormattedMessage {...globalMessages.autofill} />
      </CapLabel>);
  }
  return <></>
}

export const getWhatsappCategory = (category, hostName) => {
  const categoryMap = {
    [HOST_TWILIO]: TWILIO_CATEGORY_OPTIONS,
    [HOST_ICS]: ICS_CATEGORY_OPTIONS,
  };

  const categoryOptions = categoryMap[hostName] || [...KARIX_GUPSHUP_CATEGORY_OPTIONS, ...KARIX_GUPSHUP_OLDER_CATEGORY_OPTIONS];

  return categoryOptions?.find((obj) => obj?.value === category);
};

export const getWhatsappStatus = (status) => {
  if ([WHATSAPP_STATUSES.pending, WHATSAPP_STATUSES.unsubmitted].includes(status)) {
    status = WHATSAPP_STATUSES.awaitingApproval;
  }
  return STATUS_OPTIONS.find((obj) => obj.value === status);
};
