import React, { useEffect } from 'react';

const AMAZON_CONSENT_WIDGET_DIV_ID = 'consentWidgetDiv';

export const toBoolean = (value: any) => {
  if (typeof value === 'string') {
    if (value === 'true') {
      return true;
    }
    if (value === 'false') {
      return false;
    }
  }

  return !!value;
};

export const ConsentWidget =({
  sellerId,
  onConsent,
  onError,
  amazonBillingAgreementId
}: any) => {

  const handleConsent = (consent: any) => {
    onConsent(toBoolean(consent.getConsentStatus()));
  }

  useEffect(() => {
    //@ts-ignore
    new window.OffAmazonPayments.Widgets.Consent({
      sellerId,
      amazonBillingAgreementId,
      design: { designMode: 'responsive' },
      onConsent: handleConsent,
      onError
    }).bind(AMAZON_CONSENT_WIDGET_DIV_ID);
  }, [])

  return (
    <div
        id={AMAZON_CONSENT_WIDGET_DIV_ID}
        style={{
          height: 152,
          marginTop: 12,
          marginBottom: 18
        }}
    />
  )
}
