import React, { useState } from 'react';
import PropTypes from 'prop-types';
import useTranslate from '~hooks/useTranslate/useTranslate';
import CopyIcon from '../../../images/icons/copy-icon';
import CheckCircleIcon from '../../../images/icons/check-circle';
import styles from './coupon.module.scss';

const Coupon = ({
  code = '',
  status = 'active',
  translationKey = 'code',
  defaultTranslation = 'Code:',
  templateOne = true,
  showprefix = false,
  icon = <CopyIcon />,
  checkIcon = <CheckCircleIcon />,
  showIcon = true,
  shortCode
}) => {
  if (!code) return;

  const [copySuccess, setCopySuccess] = useState('');

  const copyToClipBoard = async (e, copyMe) => {
    e.preventDefault(); 
    e.stopPropagation(); 

    try {
      await navigator.clipboard.writeText(copyMe);
      setCopySuccess(true);
    } catch (err) {
      setCopySuccess(false);
    }
  };

  const inactive = status === 'inactive';
  const isBet365 = shortCode === 'bet365';

  return (
    <div
      className={`${styles?.couponContainer || ''} ${!templateOne ? styles.templateTwo : ''} ${
        copySuccess ? styles.copiedContainer : ''
      } `}
    >
      {!templateOne && showprefix && (
        <span className={styles.prefix}>{useTranslate(translationKey, defaultTranslation)}</span>
      )}
      <button
        onClick={(e) => (code !== null && !inactive && !isBet365 ? copyToClipBoard(e, code) : '')}
        type="button"
        className={`${styles.coupon} ${copySuccess ? styles.copied : ''} 
        ${code === null ? styles.noCode : ''}
        ${inactive ? styles.disabled : ''}`}
        disabled={inactive || isBet365}
      >
        {!copySuccess ? (
          <>
            {templateOne && showprefix && (
              <span className={styles.prefix}>
                {useTranslate(translationKey, defaultTranslation)}
              </span>
            )}
            {code || useTranslate('no_coupon_available', 'Not Needed')}
            {showIcon && code !== null && !inactive && !isBet365 && icon}
          </>
        ) : (
          <>
            <span>{useTranslate('code_copied', 'CODE COPIED')}</span>
            {showIcon && checkIcon}
          </>
        )}
      </button>
    </div>
  );
};

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

export default Coupon;
