import {
  customElement,
  DeesElement,
  property,
  html,
  cssManager,
  unsafeCSS,
  css,
} from '@design.estate/dees-element';

import * as plugins from '../../../plugins.js';
import sharedStyles from '../sharedstyles.js';
import * as state from '../../../states/accountstate.js';

declare global {
  interface HTMLElementTagNameMap {
    'lele-accountview-paddlesetup': PaddleSetupView;
  }
}

@customElement('lele-accountview-paddlesetup')
export class PaddleSetupView extends DeesElement {
  public static styles = [
    cssManager.defaultStyles,
    sharedStyles,
    css`
      :host {
        display: block;
        max-width: 900px;
        margin: auto;
        color: ${cssManager.bdTheme('#333', '#fff')};
      }
    `,
  ];

  public render() {
    return html`
      <h1>-> Paddle Setup</h1>
      <p>
        In order to use workspace.global <b>with paid features</b>, you need to setup a Paddle
        subscription. A Paddle connection is bound to an organization.
      </p>
      <p>
        The base price of a Paddle Subscription is always 0€. Any charges that occur will be billed
        as an extra charge on top of your free base subscription
        <b>on a monthly date of your choosing</b>.
      </p>
      <p>
        Since Paddle acts as merchant of record, your invoices will read Paddle as Creditor, and you
        as Debitor.
      </p>
      <h2>Why are we using Paddle?</h2>
      <p>
        Paddle takes care of tax compliance for us. This allows us to sell our products world wide
        while Paddle makes sure any sales are in compliance with local laws.
      </p>
      <dees-button>Let's do it!</dees-button>
    `;
  }

  /**
   *
   */
  public async firstUpdated() {
    await this.domtoolsPromise;
    const paddleButton = this.shadowRoot.querySelector('dees-button');
    const openPaddle = async () => {
      await this.domtools.setExternalScript('https://cdn.paddle.com/paddle/paddle.js');
      globalThis.Paddle.Setup({
        vendor: 30954,
        eventCallback: async (dataArg) => {
          // The data.event will specify the event type
          if (dataArg.event === 'Checkout.Complete') {
            const data: plugins.idpInterfaces.data.IPaddleCheckoutData = dataArg.eventData;
            const paddleIframe = document.body.querySelector('iframe');
            document.body.removeChild(paddleIframe);
            paddleButton.status = 'pending';
            paddleButton.text = 'Processing...';
            await state.accountState.dispatchAction(state.updatePaddleCheckoutId, data.checkout.id);
            paddleButton.status = 'success';
            paddleButton.text = 'Paddle connected!'
          }
        },
      });
      globalThis.Paddle.Checkout.open({
        product: 561076,
        email: 'phil@kunz.io',
      });
    };
    paddleButton.addEventListener('clicked', async () => {
      openPaddle();
    });
  }
}
