import React, { useState, useContext } from 'react';
import PropTypes from 'prop-types';
import { Context } from 'gatsby-core-theme/src/context/MainProvider';
import { translate } from 'gatsby-core-theme/src/helpers/getters';

import styles from './coupon.module.scss';

const Coupon = ({
  code = '',
  status = 'active',
  translationKey = 'code',
  defaultTranslation = 'Code:',
  templateOne = true,
  showprefix = false,
  icon = '../../../images/copyIcon.svg',
  checkIcon = '../../../images/check-circle.svg',
  showIcon = true,
}) => {
  const [copySuccess, setCopySuccess] = useState('');
  const { translations } = useContext(Context) || {};

  const copyToClipBoard = async (copyMe) => {
    try {
      await navigator.clipboard.writeText(copyMe);
      setCopySuccess(true);
    } catch (err) {
      setCopySuccess(false);
    }
  };

  const inactive = status === 'inactive';

  return (
    <div
      className={`${styles?.couponContainer || ''} ${!templateOne ? styles.templateTwo : ''} ${
        copySuccess ? styles.copiedContainer : ''
      } `}
    >
      {!templateOne && showprefix && (
        <span className={styles.prefix}>
          {translate(translations, translationKey, defaultTranslation)}
        </span>
      )}
      <button
        onClick={() => (code !== null && !inactive ? copyToClipBoard(code) : '')}
        type="button"
        className={`${styles.coupon} ${copySuccess ? styles.copied : ''} 
        ${code === null ? styles.noCode : ''}
        ${inactive ? styles.disabled : ''}`}
        disabled={inactive}
      >
        {!copySuccess ? (
          <>
            {templateOne && showprefix && (
              <span className={styles.prefix}>
                {translate(translations, translationKey, defaultTranslation)}
              </span>
            )}
            {code || translate(translations, 'no_coupon_available', 'Not Needed')}
            {showIcon && code !== null && !inactive && (
              <img src={icon} alt="Copy Icon" width={22} height={22} />
            )}
          </>
        ) : (
          <>
            <span>{translate(translations, 'code_copied', 'CODE COPIED')}</span>
            {showIcon && <img src={checkIcon} alt="Check Icon" width={22} height={22} />}
          </>
        )}
      </button>
    </div>
  );
};

Coupon.propTypes = {
  code: PropTypes.string,
  status: PropTypes.string,
  templateOne: PropTypes.bool,
  showprefix: PropTypes.bool,
  icon: PropTypes.string,
  checkIcon: PropTypes.string,
  showIcon: PropTypes.bool,
  translationKey: PropTypes.string,
  defaultTranslation: PropTypes.string,
};

export default Coupon;
