import { bridgeOpenPopupUrl } from '@/bridge/content/background';
import i18n from '@/plugins/i18n';
import { setNativeValue, appendNextNode } from '@content/service/util';
import { storagePlatformShopConfig } from '@/plugins/storage/items';
import { loggerContent } from '@/plugins/logger';

const elementFlashsaleCampaign = {
  parent: 'div.landing-page-header',
  btnBase: 'div.landing-page-header > div.landing-page-action > button.eds-button--large',
  buttonId: 'autoshopee-btn-flashsale',
};

const sellerMarketingConfig = {
  'shop-flash-sale': {
    root: 'div.detail-products-container.card-style > div.products-container-content > div > form > div > div.edit-mode',
    parent: 'div.inner-rows > div.inner-row',
    myId: 'autoshopee-btn-apply-marketing-flashsale',
    money: 'div.price-discount-input > div.currency-input > div > input.eds-input__input:not([disabled])',
    percent: 'div.price-discount-input > div.discount-input > div > input.eds-input__input:not([disabled])',
    append: 'div.item-action',
  },
  discount: {
    root: 'form.eds-form.eds-form--label-right.discount-items-table.edit-mode.no-taxable.no-pff > div> div> div > div.discount-item-component',
    parent: 'div.discount-edit-item-model-component',
    myId: 'autoshopee-btn-apply-marketing-discount',
    money: 'div.price-discount.eds-form-item > div > div > div > div.eds-input.currency-input > div > input:not([disabled])',
    percent: 'div.price-discount.eds-form-item > div > div > div > div.eds-input.discount-input > div > input:not([disabled])',
    append: 'div.item-promotion-stock',
  },
};

storagePlatformShopConfig.getValue().then((platformShopConfig) => {
  if (platformShopConfig && platformShopConfig.shopee && platformShopConfig.shopee.sellerMarketing) {
    const getConfig = platformShopConfig.shopee.sellerMarketing;

    if (getConfig['shop-flash-sale'] && getConfig['shop-flash-sale'].root) {
      sellerMarketingConfig['shop-flash-sale'] = getConfig['shop-flash-sale'];
    }

    if (getConfig.discount && getConfig.discount.root) {
      sellerMarketingConfig.discount = getConfig.discount;
    }
  }
}).catch(() => {});

/**
 *
 * @param {{btnBase: string, buttonId: string}} element
 * @returns
 */
const addButtonFLashSale = async (element) => {
  const buttonBase = document.querySelector(element.btnBase);
  const buttonFlashSale = buttonBase.cloneNode(true);
  buttonFlashSale.innerHTML = i18n.t('BTN_MARKETING_FLASHSALE_MASS');
  buttonFlashSale.id = element.buttonId;

  buttonFlashSale.style.background = 'rgb(60 0 177)';
  buttonFlashSale.style['border-color'] = 'rgb(60 0 177)';

  buttonFlashSale.addEventListener('click', async () => {
    bridgeOpenPopupUrl({
      path: '/shopee/seller/flashsale',
      qs: {},
    });
  });

  appendNextNode(buttonBase, buttonFlashSale);

  return buttonFlashSale;
};

const addIndexFlashSale = async () => {
  const elementWithClasses = document.querySelector('.router-link-active.breadcrumb-name.active');

  if (!elementWithClasses) {
    return null;
  }

  const elementButton = document.querySelector('#autoshopee-btn-flashsale-index');

  if (elementButton) {
    return null;
  }

  const buttonFlashSale = document.createElement('button');
  buttonFlashSale.type = 'button';
  buttonFlashSale.id = 'autoshopee-btn-flashsale-index';
  buttonFlashSale.innerHTML = i18n.t('BTN_MARKETING_FLASHSALE_MASS');
  buttonFlashSale.style.background = 'transparent';
  buttonFlashSale.style.color = 'rgb(60, 0, 177)';
  buttonFlashSale.style.border = 'none';
  buttonFlashSale.style.padding = '4px 8px';
  buttonFlashSale.style.margin = '0 4px';
  buttonFlashSale.style.cursor = 'pointer';

  buttonFlashSale.addEventListener('click', async () => {
    bridgeOpenPopupUrl({
      path: '/shopee/seller/flashsale',
      qs: {},
    });
  });

  appendNextNode(elementWithClasses, buttonFlashSale);

  return buttonFlashSale;
};

export const onMarketingPage = async () => {
  const urlCurrent = window.location.href;
  const urlMatch = urlCurrent.match(/\/portal\/marketing\/(.*?)\//);

  addIndexFlashSale().catch(() => {});

  if (!(urlMatch && urlMatch[1])) {
    return false;
  }

  const marketingType = urlMatch[1];

  const elementPath = sellerMarketingConfig[marketingType];

  if (!elementPath) {
    return false;
  }

  if (document.querySelector(elementFlashsaleCampaign.parent) && !document.querySelector(`#${elementFlashsaleCampaign.buttonId}`)) {
    addButtonFLashSale(elementFlashsaleCampaign).catch(() => {});
  }

  if (!document.querySelector(elementPath.root)) {
    return false;
  }

  document.querySelectorAll(elementPath.root).forEach((
  /**
   * @type {HTMLElement}
   */
    elmentRoot,
  ) => {
    try {
      if (elmentRoot.querySelector(elementPath.parent).querySelector(elementPath.append).querySelector(`#${elementPath.myId}`)) {
        return false;
      }

      const handlerMassValue = (type) => {
        const money = Number(elmentRoot.querySelector(elementPath.parent).querySelector(elementPath.money).value);
        const percent = Number(elmentRoot.querySelector(elementPath.parent).querySelector(elementPath.percent).value);
        elmentRoot.querySelectorAll(elementPath.parent).forEach((elItem) => {
          try {
            const elementInput = elementPath[type] || '';
            const valueInput = type === 'percent' ? percent : type === 'money' ? money : 0;

            if (elementInput) {
              setNativeValue(elItem.querySelector(elementInput), valueInput);
            }
          } catch (error) {
            loggerContent.error({
              msg: 'MARKETING_MASS_SET_ERROR',
              error,
            });
          }
        });
      };

      const containerBtn = document.createElement('div');
      const baseBtn = document.createElement('button');
      baseBtn.id = elementPath.myId;
      baseBtn.type = 'button';
      baseBtn.title = i18n.t('AUTOSHOPEE_COPYRIGHT');
      baseBtn.style = ['color: #fff', 'padding:5px', 'background: rgb(60, 0, 177)', 'border-radius: 3px', 'margin-bottom:5px', 'margin-right:5px', 'cursor: pointer'].join(';');

      const elementBtnDiscount = baseBtn.cloneNode();
      const elementBtnMoney = baseBtn.cloneNode();
      elementBtnDiscount.innerText = 'Copy %';

      elementBtnDiscount.onclick = () => {
        handlerMassValue('percent');
      };

      elementBtnMoney.innerText = 'Copy $';

      elementBtnMoney.onclick = () => {
        handlerMassValue('money');
      };

      containerBtn.append(elementBtnDiscount);
      containerBtn.append(elementBtnMoney);

      elmentRoot.querySelector(elementPath.parent).querySelector(elementPath.append).prepend(containerBtn);
    } catch (error) {
      loggerContent.error({
        msg: 'MARKETING_MASS_CONTAINER_ERROR',
        error,
      });
    }
  });
};
