import React, { useState, useEffect } from "react";
import axios from "axios";
import VisibilityIcon from '@mui/icons-material/Visibility';
import VisibilityOffIcon from '@mui/icons-material/VisibilityOff';
import PlayCircleIcon from '@mui/icons-material/PlayCircle';
import ReactSwitchreview from 'react-switch'
import ReactSwitchsupport from 'react-switch'
import ReactPlayer from 'react-player'
import woo from '../../../assets/icons/support/woo.png'
import Modal from '../Modal/Modal';
import HelpOutlineIcon from '@mui/icons-material/HelpOutline';
import { InstallingLoader } from '../../icons';
import Tippy from '@tippy.js/react';
import 'tippy.js/dist/tippy.css'
import { isPro, getNonce, isWooactive, getNoticeData } from '../../Helpers';
import orderStatus from '../../../assets/order-status.gif'
import 'tippy.js/dist/tippy.css'
import NoticeModal from '../NoticeModal/NoticeModal';
import "./woocommerce.scss";

const WooCommerce = ({ noticeSettings }) => {
  const [modalOpen, setModalOpen] = useState(false);
  const [passview, setPassview] = useState(false);
  const [iswooactive, setIswooactive] = useState(isWooactive());
  const [wooloading, setWOOLoading] = useState(false);
  const [credentials, setCredentials] = useState([]);
  const [getGlobalURL, setGetGlobalURL] = useState(false);
  const proData = isPro();

  const allConditionsMet = proData;

  const [modalConfig, setModalConfig] = useState({
    isOpen: false,
    type: 'confirmation',
    title: '',
    message: '',
    onConfirm: () => { },
    confirmText: 'Confirm',
    declineText: 'Cancel'
  });
  const closeModal = () => {
    setModalConfig(prev => ({ ...prev, isOpen: false }));
  };
  // Extract the last part of the URL as the site identifier
  const pathParts = window.location.pathname.split("/").filter(Boolean);
  const indexOfAdmin = pathParts.indexOf('wp-admin');
  const siteIdentifier = indexOfAdmin !== -1 ? pathParts.slice(indexOfAdmin - 1, indexOfAdmin).pop() : pathParts.slice(-1).pop();
  // Use the site identifier to create a unique localStorage key
  const localStorageKey = `wpnts_woocommerce_settings_${siteIdentifier}`;
  //END ------------------


  const handleViewpass = () => {
    passview === true ? setPassview(false) : setPassview(true)
  }


  useEffect(() => {
    getWebhook();
  }, []);

  function getWebhook() {
    const wpnts_woocommerce_settings = getNoticeData().wpnts_schedules_interval_woocommerce_settings || {
      webhook: "",
      intervalDays: -1,
      billingshippingnotify: false,
      ordernotmarkedstatus: false,
      ordernotmarkedstatus_interval_notification: 2,
      shipingstatus: false,
      stockorout_interval_notification: '',
      stockoutofstocknotifications: false,
      productdownloadnotice: false,

    };

    const formData = JSON.parse(localStorage.getItem(localStorageKey) || JSON.stringify(wpnts_woocommerce_settings));
    setCredentials(formData);
  }



  const [wpntswebhook_woocommerce_settings, setWebhook] = useState({
    webhook: credentials.webhook,
    stockorout_interval_notification: credentials.stockorout_interval_notification,
    ordernotmarkedstatus_interval_notification: credentials.ordernotmarkedstatus_interval_notification,
    intervalDays: credentials.intervalDays,
    salesnotifications: credentials.salesnotifications,
    ordernotmarkedstatus: credentials.ordernotmarkedstatus,

    stockoutofstocknotifications: credentials.stockoutofstocknotifications,

    couponusesnotification: credentials.couponusesnotification,

    wooproducteditornotify: credentials.wooproducteditornotify,
    shipingstatus: credentials.shipingstatus,
    billingshippingnotify: credentials.billingshippingnotify,
    productdownloadnotice: credentials.productdownloadnotice,

  });

  const handleGetGlobalURLChange = () => {
    // const globalSlack = getNoticeData().wpnts_global_api_settings.global_webhook ?? '';
    const globalSlack = noticeSettings.wpnts_global_api_settings.global_webhook ?? '';
    setWebhook(prev => ({ ...prev, webhook: globalSlack }))
  };

  const handleChange = e => {
    setWebhook(prev => ({ ...prev, [e.target.name]: e.target.value }))
  }



  const handleSalesnotifications = e => {
    setWebhook(prev => ({ ...prev, salesnotifications: e }));
  }


  const handleOrdernotmarkedstatus = e => {

    if (!allConditionsMet) {
      setModalConfig({
        isOpen: true,
        type: 'premium',
        title: '🚀 Oops! This is a Premium Feature ',
        message: 'Evaluate the features and select a bundle based on your needs.',
        onConfirm: () => {
          window.open('https://functiondeck.com/pricing/', '_blank');
          closeModal();
        },
        confirmText: 'Upgrade Now',
        declineText: 'Maybe Later'
      });
      return;
    }
    setWebhook(prev => ({ ...prev, ordernotmarkedstatus: e }));
  }


  const handleStockoutofstocknotifications = e => {
    setWebhook(prev => ({ ...prev, stockoutofstocknotifications: e }));
  }


  const handleCouponusesNotification = e => {
    if (!allConditionsMet) {
      setModalConfig({
        isOpen: true,
        type: 'premium',
        title: '🚀 Oops! This is a Premium Feature ',
        message: 'Evaluate the features and select a bundle based on your needs.',
        onConfirm: () => {
          window.open('https://functiondeck.com/pricing/', '_blank');
          closeModal();
        },
        confirmText: 'Upgrade Now',
        declineText: 'Maybe Later'
      });
      return;
    }
    setWebhook(prev => ({ ...prev, couponusesnotification: e }));
  }

  const handleWooproducteditornotify = e => {
    setWebhook(prev => ({ ...prev, wooproducteditornotify: e }));
  }

  const handleBillingshippingnotify = e => {

    setWebhook(prev => ({ ...prev, billingshippingnotify: e }));
  }

  const handleProductdownloadnotice = e => {
    if (!allConditionsMet) {
      setModalConfig({
        isOpen: true,
        type: 'premium',
        title: '🚀 Oops! This is a Premium Feature ',
        message: 'Evaluate the features and select a bundle based on your needs.',
        onConfirm: () => {
          window.open('https://functiondeck.com/pricing/', '_blank');
          closeModal();
        },
        confirmText: 'Upgrade Now',
        declineText: 'Maybe Later'
      });
      return;
    }
    setWebhook(prev => ({ ...prev, productdownloadnotice: e }));
  }

  const handleShipingstatus = e => {

    setWebhook(prev => ({ ...prev, shipingstatus: e }));
  }


  useEffect(() => {
    setWebhook({
      webhook: credentials.webhook,
      stockorout_interval_notification: credentials.stockorout_interval_notification,
      ordernotmarkedstatus_interval_notification: credentials.ordernotmarkedstatus_interval_notification,
      intervalDays: credentials.intervalDays,
      salesnotifications: credentials.salesnotifications,
      ordernotmarkedstatus: credentials.ordernotmarkedstatus,

      stockoutofstocknotifications: credentials.stockoutofstocknotifications,

      couponusesnotification: credentials.couponusesnotification,

      wooproducteditornotify: credentials.wooproducteditornotify,
      shipingstatus: credentials.shipingstatus,
      billingshippingnotify: credentials.billingshippingnotify,
      productdownloadnotice: credentials.productdownloadnotice,

    });
  }, [credentials]);


  const handleIntervalDays = (e) => {
    const selectedInterval = parseInt(e.target.value, 10);
    setWebhook((prev) => ({
      ...prev,
      intervalDays: selectedInterval,
    }));
  }
  const handleStockUpdateinterval = (e) => {
    const selectedInterval = parseInt(e.target.value, 10);
    setWebhook((prev) => ({
      ...prev,
      stockorout_interval_notification: selectedInterval,
    }));
  }

  const handleOrdernotcompleteinterval = (e) => {
    const selectedInterval = parseInt(e.target.value, 10);
    setWebhook((prev) => ({
      ...prev,
      ordernotmarkedstatus_interval_notification: selectedInterval,
    }));
  }



  const activateWoocommerce = () => {
    wp.ajax.send('activate_woocommerce_plugin', {
      data: {
        nonce: getNonce(),
      },
      success(response) {

        setWOOLoading(false); // Hide loader
        handleCheckisWoocommerceactiverecent();
      },
      error(error) {

        setWOOLoading(false); // Hide loader
        handleCheckisWoocommerceactiverecent();
      },
    });
  };

  const installAndActivateWoocommerce = () => {
    wp.ajax.send('install_and_activate_woocommerce_plugin', {
      data: {
        nonce: getNonce(),
      },
      success(response) {

        setWOOLoading(false); // Hide loader
        handleCheckisWoocommerceactiverecent();
      },
      error(error) {

        setWOOLoading(false); // Hide loader
        handleCheckisWoocommerceactiverecent();
      },
    });
  };


  //After install need to refetch the data to show on without page load
  const handleCheckisWoocommerceactiverecent = () => {
    wp.ajax.send('nts_is_woocommerce_installed', {
      data: {
        nonce: getNonce(),
      },
      success(response) {

        setIswooactive(response.status);
      },
      error(error) {
        console.error(error);
      },
    });

  };

  useEffect(() => {
    wp.ajax.send('nts_is_woocommerce_installed', {
      data: {
        nonce: getNonce(),
      },
      success(response) {

        setIswooactive(response.status);
      },
      error(error) {
        console.error(error);
      },
    });
  }, []);





  /**
   * SAVE
   * 
   */
  const handleSave = async e => {
    e.preventDefault()
    localStorage.setItem(localStorageKey, JSON.stringify(wpntswebhook_woocommerce_settings));

    /**
     * Add new plugin list name.
     */
    const url = `${appLocalizer.wpntsUrl}/wpnts/v1/slack_webhook_interval_woocommerce_settings`;
    try {
      const res = await axios.post(url, {
        wpntswebhook_woocommerce_settings
      }, {
        headers: {
          'content-type': 'application/json',
          'X-WP-NONCE': appLocalizer.nonce
        }
      }).then(function (res) {
        // console.log(wpntswebhook_woocommerce_settings)
      });

    } catch (err) {
      console.log(err);
    }


    setModalConfig({
      isOpen: true,
      type: 'toast',
      title: 'success',
      message: 'Webhook configure successfully',
      position: 'top-right'
    });
    setTimeout(closeModal, 3000);

  }

  return (
    <div className={`acb_woocommerce ${iswooactive ? '' : 'inactive'}`} id='acb_woocommerce'>
      <div className="acb_left">
        <h3>WooCommerce settings panel
          <a href="https://www.youtube.com/playlist?list=PL4m92NgWQaq5ttBH9gSYUX1r4c6rtgLg9" target="_blank"><PlayCircleIcon className='PlayCircleIcon' /></a>
        </h3>
        <br />


        <div className="woocommerce-settings">
          <div className="wpnts-switch-stockoutofstocknotifications">

            <div className="parent-section">
              <div className="toogle-section">
                <ReactSwitchsupport uncheckedIcon checkedIcon className="woo-supportSwitch-3" name="wpnts-switch-p-deactivation" id="stockoutofstocknotifications" onChange={handleStockoutofstocknotifications} checked={wpntswebhook_woocommerce_settings.stockoutofstocknotifications} height={20} width={40} boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
                  activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)" />
                <label htmlFor="stockoutofstocknotifications">Product stock, out of stock Notifications:</label>
                <Tippy content="You will be notified when any product on your website is out of stock or newly in stock">
                  <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                </Tippy>
              </div>

              <div className="section-child">
                {/* {wpntswebhook_woocommerce_settings.stockoutofstocknotifications ?
                  <div className="formInput">
                    <label htmlFor="intervalDays">Add any days to send update notification [ optionals ] </label>
                    <div className="wpnts-setting">
                      <select
                        name="intervalDays"
                        required
                        onChange={handleIntervalDays}
                        value={wpntswebhook_woocommerce_settings.intervalDays}
                        className="woo-select-fields"
                      >
                        <option value={-1}>From last 1 days</option>
                        <option value={-5}>5 days</option>
                        <option value={-7}>7 days</option>
                        <option value={-10}>10 days</option>
                        <option value={-15}>15 days</option>
                        <option value={-20}>20 days</option>
                        <option value={-30}>30 days</option>
                      </select>
                    </div>
                  </div>
                  : ''} */}

                {wpntswebhook_woocommerce_settings.stockoutofstocknotifications ?
                  <div className="formInput">
                    <label htmlFor="stockorout_interval_notification">Time Interval for sending the notification</label>
                    <div className="wpnts-setting">
                      <select
                        name="stockorout_interval_notification"
                        required
                        onChange={handleStockUpdateinterval}
                        value={wpntswebhook_woocommerce_settings.stockorout_interval_notification}
                        className="woo-select-fields"
                      >
                        <option value={60}>1 min interval</option>
                        <option value={180}>3 min</option>
                        <option value={300}>5 min</option>
                        <option value={1800}>30 min</option>
                        <option value={3600}>1 hour</option>
                        <option value={18000}>5 hours</option>
                        <option value={36000}>10 hours</option>
                        <option value={54000}>15 hours</option>
                        <option value={64800}>18 hours</option>
                        <option value={86400}>24 hours</option>
                        <option value={172800}>2 days</option>
                        <option value={259200}>3 days</option>
                        <option value={604800}>7 days</option>
                      </select>

                    </div>
                  </div>
                  : ''}

              </div>

            </div>

          </div>


          <div className="wpnts-switch-salesnotifications">
            {/* {!allConditionsMet ? <p className="PRO_TAG">PRO</p> : ''} */}
            <div className={`woo-free-feature`}>
              <ReactSwitchsupport uncheckedIcon checkedIcon className="woo-supportSwitch-2" name="wpnts-switch-p-activation" id="salesnotifications" onChange={handleSalesnotifications} checked={wpntswebhook_woocommerce_settings.salesnotifications} height={20} width={40} boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
                activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)" />
              <label htmlFor="salesnotifications">Sales Notifications to Slack:</label>
              <Tippy content="If a product is sold or the status of the product changes, you will be notified along with the product details">
                <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
              </Tippy>

            </div>
          </div>


          {/* NEW  */}
          <div className="wpnts-switch-commentmoderationnotifications">
            <div className={`woo-free-feature`}>
              <ReactSwitchsupport uncheckedIcon checkedIcon className="woo-supportSwitch-4" name="wpnts-wooproducteditornotify" id="wooproducteditornotify" onChange={handleWooproducteditornotify} checked={wpntswebhook_woocommerce_settings.wooproducteditornotify} height={20} width={40} boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
                activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)" />
              <label htmlFor="wooproducteditornotify">Product editor notification:</label>
              <Tippy content="You will be notified when WooCommerce product title, description,SKU, Stock, weight, price, product image,Product Gallery,Product Type,Stock Status,Product Categories,Tags any of the field updated or modified by any one.">
                <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
              </Tippy>

            </div>
          </div>


          <div className="wpnts-switch-commentmoderationnotifications">
            {/* {!allConditionsMet ? <p className="PRO_TAG">PRO</p> : ''} */}
            {/* <p className="NEW_TAGs">New</p> */}
            <div className={`woo-free-feature`}>
              <ReactSwitchsupport uncheckedIcon checkedIcon className="woo-supportSwitch-4" name="wpnts-shipingstatus" id="shipingstatus" onChange={handleShipingstatus} checked={wpntswebhook_woocommerce_settings.shipingstatus} height={20} width={40} boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
                activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)" />
              <label htmlFor="shipingstatus">Shipping status notification:</label>
              <Tippy content="You will be notified when WooCommerce product shipping status updated for any product.">
                <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
              </Tippy>

            </div>
          </div>

          {/* Billing Shipping Address change */}
          <div className="wpnts-switch-commentmoderationnotifications">
            {/* {!allConditionsMet ? <p className="PRO_TAG">PRO</p> : ''} */}
            {/* <p className="NEW_TAGs">New</p> */}
            <div className={`woo-free-feature`}>
              <ReactSwitchsupport uncheckedIcon checkedIcon className="woo-supportSwitch-4" name="wpnts-billingshippingnotify" id="billingshippingnotify" onChange={handleBillingshippingnotify} checked={wpntswebhook_woocommerce_settings.billingshippingnotify} height={20} width={40} boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
                activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)" />
              <label htmlFor="billingshippingnotify">Billing & Shipping Address notification:</label>
              <Tippy content="You will be notified when users billing or shipping address updated or modified by user or anyone.">
                <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
              </Tippy>

            </div>
          </div>

          <div className="wpnts-switch-salesnotifications">
            {!allConditionsMet ? <p className="PRO_TAG">PRO</p> : ''}
            {/* <p className="NEW_TAGs">New</p> */}
            <div className={`wpnts_ispro ${allConditionsMet ? '' : 'inactive'}`}>

              <div className="parent-section">
                <div className="toogle-section">
                  <ReactSwitchsupport uncheckedIcon checkedIcon className="woo-supportSwitch-2" name="wpnts-switch-p-activation" id="ordernotmarkedstatus" onChange={handleOrdernotmarkedstatus} checked={wpntswebhook_woocommerce_settings.ordernotmarkedstatus} height={20} width={40} boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
                    activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)" />
                  <label htmlFor="ordernotmarkedstatus">Order not completed reminder:</label>
                  <Tippy content="If a product is not marked as complete after specified days, you will be notified along with the product details">
                    <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
                  </Tippy>
                </div>

                <div className="section-child">
                  {wpntswebhook_woocommerce_settings.ordernotmarkedstatus ?
                    <div className="formInput">
                      <label htmlFor="ordernotmarkedstatus_interval_notification">Specified days Order not complete reminder</label>
                      <div className="wpnts-setting">
                        <select
                          name="ordernotmarkedstatus_interval_notification"
                          required
                          onChange={handleOrdernotcompleteinterval}
                          value={wpntswebhook_woocommerce_settings.ordernotmarkedstatus_interval_notification}
                          className="woo-select-fields"
                        >
                          <option value={60}>1 min</option>
                          <option value={300}>5 min</option>
                          <option value={1800}>30 min</option>
                          <option value={3600}>1 hour</option>
                          <option value={43200}>12 hours</option>
                          <option value={1}>1 days interval</option>
                          <option value={2}>2 days</option>
                          <option value={3}>3 days</option>
                          <option value={4}>4 days</option>
                          <option value={5}>5 days</option>
                          <option value={6}>6 hour</option>
                          <option value={7}>7 days</option>
                          <option value={8}>8 days</option>
                          <option value={9}>9 days</option>
                          <option value={10}>10 days</option>
                        </select>

                      </div>
                    </div>
                    : ''}
                </div>
              </div>
            </div>
          </div>

          <div className="wpnts-switch-commentmoderationnotifications">
            {!allConditionsMet ? <p className="PRO_TAG">PRO</p> : ''}
            {/* <p className="NEW_TAGs">New</p> */}
            <div className={`wpnts_ispro ${allConditionsMet ? '' : 'inactive'}`}>
              <ReactSwitchsupport uncheckedIcon checkedIcon className="woo-supportSwitch-4" name="wpnts-couponusesnotification" id="couponusesnotification" onChange={handleCouponusesNotification} checked={wpntswebhook_woocommerce_settings.couponusesnotification} height={20} width={40} boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
                activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)" />
              <label htmlFor="couponusesnotification">Coupon uses notification:</label>
              <Tippy content="You will be notified when WooCommerce coupon is used by any user. It will send user name with Coupon code and purchase product name.">
                <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
              </Tippy>

            </div>
          </div>


          {/* Product download  */}
          <div className="wpnts-switch-commentmoderationnotifications">
            {!allConditionsMet ? <p className="PRO_TAG">PRO</p> : ''}
            {/* <p className="NEW_TAGs">New</p> */}
            <div className={`wpnts_ispro ${allConditionsMet ? '' : 'inactive'}`}>
              <ReactSwitchsupport uncheckedIcon checkedIcon className="woo-supportSwitch-4" name="wpnts-productdownloadnotice" id="productdownloadnotice" onChange={handleProductdownloadnotice} checked={wpntswebhook_woocommerce_settings.productdownloadnotice} height={20} width={40} boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
                activeBoxShadow="0px 0px 1px 10px rgba(0, 0, 0, 0.2)" />
              <label htmlFor="productdownloadnotice">My Account page downloads notice:</label>
              <Tippy content="You will be notified when users download any files from the 'Downloads'">
                <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
              </Tippy>

            </div>
          </div>


          {(iswooactive === 'inactive' || iswooactive === 'notinstalled') && (
            <div className="inactive-overlay">
              <div className="action-btns">
                <div className="inactive-header">
                  <img className='wpnts_woocommerce' src={woo} alt="woocommerce" />

                </div>
                <div className="install-btn">
                  <h3 className="inactive-text">Please {iswooactive === 'inactive' ? 'Activate' : 'Install'} WooCommerce</h3>

                </div>
              </div>
            </div>
          )}


        </div>


      </div>
      <div className="acb_right">
        <form action="" id="wpnts_woocommerce_settings">
          <div className="formInput">
            <label htmlFor="webhook">Webhook URL</label>
            <div className="wpnts-setting">
              <div className="passimg" onClick={handleViewpass}>
                {passview === false ? <VisibilityOffIcon className='passVisibility' /> : <VisibilityIcon className='passVisibility' />}
              </div>
              <input type={passview === true ? "text" : "password"} placeholder="add webhook " name="webhook" required onChange={handleChange} value={wpntswebhook_woocommerce_settings.webhook} />
            </div>
          </div>

          <div className="getGlobalURLCheckbox">
            <input
              type="checkbox"
              id="getGlobalURL"
              checked={getGlobalURL}
              onChange={handleGetGlobalURLChange}
            />
            <label htmlFor="getGlobalURL">Click to get slack global webhook</label>
          </div>

          <button className="save-webhook" onClick={handleSave}>SAVE</button>
        </form>

      </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}
      />

      {modalOpen && <><div class="wcs_popup_overlay"></div> <Modal setOpenModal={setModalOpen} /> </>}
    </div>

  )
}

export default WooCommerce
