import React, { useState, useEffect, useRef } from 'react'
import axios from "axios";
import Countdown from 'react-countdown';
import NoticeModal from '../NoticeModal/NoticeModal';
import facebook from '../../../assets/icons/support/facebook.svg';
import wpxpertise from '../../../assets/icons/support/logo-site.png'
import twitter from '../../../assets/icons/support/twitter-x-fill.svg';
import gmailicon from '../../../assets/icons/support/gmail.svg';
import defaultEmail from '../../../assets/icons/support/default-email.svg';
import iconmark from '../../../assets/icons/support/iconmark.svg';
import supportmail from '../../../assets/icons/support/supportmail.svg';
import './modal.scss'

const Modal = ({ setOpenModal }) => {
  const modalRef = useRef();
  const [modalConfig, setModalConfig] = useState({
    isOpen: false,
    type: 'confirmation',
    title: '',
    message: '',
    onConfirm: () => { },
    confirmText: 'Confirm',
    declineText: 'Cancel'
  });

  const closeModal = () => {
    setModalConfig(prev => ({ ...prev, isOpen: false }));
  };
  const [copySuccess, setCopySuccess] = useState(false);

  const handleClosePopup = () => {
    setOpenModal(false);
  };

  const addContact = async e => {
    window.open('https://functiondeck.com/', '_blank');
  }

  /**
   * Alert if clicked on outside of the modal
   *
   * @param  event
   */
  function handleCancelOutside(event) {
    if (modalRef.current && !modalRef.current.contains(event.target)) {
      handleClosePopup();
    }
  }

  useEffect(() => {
    document.addEventListener('mousedown', handleCancelOutside);
    return () => {
      document.removeEventListener('mousedown', handleCancelOutside);
    };
  }, []);

  const openGmailCompose = () => {
    const email = 'functiondeck@gmail.com';
    const subject = 'Add your mail';
    const body = 'I am interested to buy your product please let me know the details';
    const gmailComposeUrl = `https://mail.google.com/mail/u/0/?view=cm&fs=1&to=${encodeURIComponent(
      email
    )}&su=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
    window.open(gmailComposeUrl, '_blank');
  };

  const openFacebookInBrowser = () => {
    window.open('https://www.facebook.com/profile.php?id=100092565099553', '_blank');
  };
  const openTwiterInBrowser = () => {
    window.open('https://x.com/FunctionDeck', '_blank');
  };

  const handleDefaultmailClick = (email, subject = '', body = '') => {
    window.location.href = `mailto:${email}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
  };

  const handleCopyMail = async (mail) => {
    try {
      // Use a more reliable method for copying
      const textArea = document.createElement('textarea');
      textArea.value = mail;

      // Make the textarea out of viewport
      textArea.style.position = 'fixed';
      textArea.style.left = '-999999px';
      textArea.style.top = '-999999px';
      document.body.appendChild(textArea);

      // Select and copy the text
      textArea.focus();
      textArea.select();
      const success = document.execCommand('copy');

      // Clean up
      document.body.removeChild(textArea);

      if (success) {
        setCopySuccess(true);
        setModalConfig({
          isOpen: true,
          type: 'toast',
          title: 'Success!',
          message: 'Email copied to clipboard',
          position: 'top-right'
        });
      } else {
        throw new Error('Copy command failed');
      }

      // Try the clipboard API as fallback if available
      if (!success && navigator.clipboard) {
        await navigator.clipboard.writeText(mail);
        setCopySuccess(true);
        setModalConfig({
          isOpen: true,
          type: 'toast',
          title: 'Success!',
          message: 'Email copied to clipboard',
          position: 'top-right'
        });
      }

      setTimeout(closeModal, 3000);
    } catch (err) {
      console.error('Copy failed:', err);
      setCopySuccess(false);
      setModalConfig({
        isOpen: true,
        type: 'toast',
        title: 'Error',
        message: 'Could not copy email to clipboard',
        position: 'top-right'
      });
      setTimeout(closeModal, 3000);
    }
  };


  return (
    <div className="wcsmodalBackground">
      <div className='support-body' ref={modalRef}>
        <div className="spt-header">
          <div className="brandlogo">
            <img className='wpnts_brandlogo' src={wpxpertise} onClick={addContact} alt="logo" />
            <div className='close'>
              <button
                onClick={() => { setOpenModal(false); }}>X</button>
            </div>
          </div>
          <h3>Contact us for Premium Support and Queries</h3>
        </div>
        <div className="spt-content">
          <div className="template">
            <div className="logo">
              <img src={gmailicon} alt="gmailicon" />
            </div>
            <div className="content" onClick={openGmailCompose}>
              <div className="spt-title">Gmail</div>
              <div className="spt-details">Open Gmail in browser</div>
            </div>
            <div className='iconmark'>
              <img src={iconmark} alt="iconmark" />
            </div>
          </div>

          <div className="template">
            <div className="logo facebook">
              <img src={facebook} alt="yahoo" />
            </div>
            <div className="content" onClick={openFacebookInBrowser}>
              <div className="spt-title">Facebook</div>
              <div className="spt-details">Reach us at Facebook</div>
            </div>
            <div className='iconmark'>
              <img src={iconmark} alt="iconmark" />
            </div>
          </div>

          <div className="template">
            <div className="logo facebook">
              <img src={twitter} alt="yahoo" />
            </div>
            <div className="content" onClick={openTwiterInBrowser}>
              <div className="spt-title">Twitter</div>
              <div className="spt-details">Reach us at X</div>
            </div>
            <div className='iconmark'>
              <img src={iconmark} alt="iconmark" />
            </div>
          </div>


          <div className="template" onClick={() => handleDefaultmailClick('functiondeck@gmail.com', 'WP Notifier to Slack', 'Facing problem in WP Notifier to Slack')}>
            <div className="logo">
              <img src={defaultEmail} alt="defaultEmail" />
            </div>
            <div className="content">
              <div className="spt-title">Default Email App</div>
              <div className="spt-details">Open your default email app</div>
            </div>
            <div className='iconmark'>
              <img src={iconmark} alt="iconmark" />
            </div>
          </div>

          <div className="template" onClick={() => handleCopyMail('functiondeck@gmail.com')}>
            <div className="logo">
              <img src={supportmail} alt="supportmail" />
            </div>
            <div className="content">
              <div className="spt-title">FunctionDeck</div>
              <div className="spt-details">Copy email address to your clipboard</div>
            </div>
            <div className='iconmark'>
              <img src={iconmark} alt="iconmark" />
            </div>
          </div>

        </div>
        <div className="spt-footer">
          <code className='support'>Need free supports, create it on <a href='https://wordpress.org/support/plugin/notifier-to-slack/' target='_blank'>WP Support</a> forum</code>
          <h4 className="spt-footer-content">powered by <a href='https://functiondeck.com/' target="_blank">FunctionDeck</a></h4>
        </div>
      </div>
      <NoticeModal
        isOpen={modalConfig.isOpen}
        onClose={closeModal}
        onConfirm={modalConfig.onConfirm}
        onDecline={closeModal}
        type={modalConfig.type}
        title={modalConfig.title}
        message={modalConfig.message}
        confirmText={modalConfig.confirmText}
        declineText={modalConfig.declineText}
        position={modalConfig.position || 'center'}
        autoClose={modalConfig.type === 'toast'}
        autoCloseTime={3000}
      />
    </div>
  )
}

export default Modal