import React, { useState, useEffect } from "react";
import ReactPlayer from 'react-player'
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 Modal from '../Modal/Modal';
import { isPro, globalhook, getNoticeData } from '../../Helpers';
import HelpOutlineIcon from '@mui/icons-material/HelpOutline';
import orderStatus from '../../../assets/order-status.gif'
import Tippy from '@tippy.js/react';
import 'tippy.js/dist/tippy.css'
import NoticeModal from '../NoticeModal/NoticeModal';
import "./author.scss";

const Author = ({ noticeSettings }) => {
  const [modalOpen, setModalOpen] = useState(false);
  const [passview, setPassview] = useState(false);
  const [credentials, setCredentials] = useState([]);
  const [getGlobalURL, setGetGlobalURL] = useState(false);
  const proData = isPro();
  const allConditionsMet = proData;


  // 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_author_settings_${siteIdentifier}`;
  //END ------------------

  const [modalConfig, setModalConfig] = useState({
    isOpen: false,
    type: 'confirmation',
    title: '',
    message: '',
    onConfirm: () => { },
    confirmText: 'Confirm',
    declineText: 'Cancel'
  });

  const closeModal = () => {
    setModalConfig(prev => ({ ...prev, isOpen: false }));
  };

  const handleViewpass = () => {
    passview === true ? setPassview(false) : setPassview(true)
  }

  useEffect(() => {
    getWebhook();
  }, []);

  function getWebhook() {
    const wpnts_authors_settings = getNoticeData().wpnts_default_interval || {
      webhook: "",
      interval: "",
      interval_review: "",
      reviewDays: -7,
    };

    const formData = JSON.parse(localStorage.getItem(localStorageKey) || JSON.stringify(wpnts_authors_settings));
    setCredentials(formData);
  }


  const [wpntswebhook, setWebhook] = useState({
    webhook: credentials.webhook,
    globalSettings: credentials.globalSettings,
    // authorPaneltoMail: credentials.authorPaneltoMail,
    interval: credentials.interval,
    interval_review: credentials.interval_review,
    reviewDays: credentials.reviewDays,
    activereview: credentials.activereview,
    activesupport: credentials.activesupport,
    active_review_hiked: credentials.active_review_hiked,
    plugin_detail_info: credentials.plugin_detail_info,
    activeinstallation: credentials.activeinstallation,
    activeinstantsupport: credentials.activeinstantsupport,
    activeinstantreview: credentials.activeinstantreview,
    weeklydownload: credentials.weeklydownload,
  });


  const handleGetGlobalURLChange = () => {
    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 handleActivatereview = e => {
    setWebhook(prev => ({ ...prev, activereview: e }));

  }

  const handleActivatesupport = e => {
    setWebhook(prev => ({ ...prev, activesupport: e }));
  }
  const handleActivereviewhiked = e => {
    setWebhook(prev => ({ ...prev, active_review_hiked: e }));
  }
  const handleWeeklyPluginInfo = e => {
    setWebhook(prev => ({ ...prev, plugin_detail_info: e }));
  }
  const handleActiveinstallation = e => {
    setWebhook(prev => ({ ...prev, activeinstallation: e }));
  }


  const handleUseGlobalSettings = (e) => {
    const isChecked = event.target.checked;
    setWebhook((prev) => ({
      ...prev,
      globalSettings: isChecked,
    }));
  }


  const handleActivateInstantsupport = 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, activeinstantsupport: e }));
  }
  const handleActivateInstantreview = 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, activeinstantreview: e }));
  }

  //PRO
  const handleWeeklydownload = 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, weeklydownload: e }));
  }

  const handleIntervalReview = (e) => {
    const selectedInterval = parseInt(e.target.value, 10);
    setWebhook((prev) => ({
      ...prev,
      interval_review: selectedInterval
    }));
  }

  const handleInterval = (e) => {
    const selectedInterval = parseInt(e.target.value, 10);
    setWebhook((prev) => ({
      ...prev,
      interval: selectedInterval,
    }));
  }

  const handleIntervalDays = (e) => {
    const selectedInterval = parseInt(e.target.value, 10);
    setWebhook((prev) => ({
      ...prev,
      reviewDays: selectedInterval,
    }));
  }


  useEffect(() => {
    setWebhook({
      webhook: credentials.webhook,
      globalSettings: credentials.globalSettings,
      // authorPaneltoMail: credentials.authorPaneltoMail,
      interval: credentials.interval, //support interval
      interval_review: credentials.interval_review,
      reviewDays: credentials.reviewDays,
      activereview: credentials.activereview,
      activesupport: credentials.activesupport,
      active_review_hiked: credentials.active_review_hiked,
      plugin_detail_info: credentials.plugin_detail_info,
      activeinstallation: credentials.activeinstallation,
      activeinstantsupport: credentials.activeinstantsupport,
      activeinstantreview: credentials.activeinstantreview,
      weeklydownload: credentials.weeklydownload,
    });
  }, [credentials]);


  const handleSave = async e => {
    e.preventDefault()
    localStorage.setItem(localStorageKey, JSON.stringify(wpntswebhook));
    /**
     * Add new plugin list name 
     * 
     */
    const url = `${appLocalizer.wpntsUrl}/wpnts/v1/slack_webhook_interval`;
    try {
      const res = await axios.post(url, {
        wpntswebhook

      }, {
        headers: {
          'content-type': 'application/json',
          'X-WP-NONCE': appLocalizer.nonce
        }
      }).then(function (res) {
        // console.log(wpntswebhook)
      });

    } catch (err) {
      console.log(err);
    }


    setModalConfig({
      isOpen: true,
      type: 'toast',
      title: 'Author configuration!',
      message: 'Author settings configure successfully',
      position: 'top-right'
    });
    setTimeout(closeModal, 3000);

  }
  return (
    <div className="acb_author" id='acb_author'>
      <div className="acb_left">
        <h3 className="review-case-title">Plugin author settings panel
          <a href="https://www.youtube.com/playlist?list=PL4m92NgWQaq5ttBH9gSYUX1r4c6rtgLg9" target="_blank"><PlayCircleIcon className='PlayCircleIcon' /></a>

        </h3>
        <br />

        <div className="wpnts-switch-review">
          <div className="parent-section">
            <div className="toogle-section">
              <ReactSwitchreview uncheckedIcon checkedIcon className="reviewSwitch-0" name="wpnts-switch-review" id="reviewnoti" onChange={handleActivatereview} checked={wpntswebhook.activereview} 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="reviewnoti">Enable Review notification: </label>
              <Tippy content="Send review notifications in Slack based on the intervals and days specified. It will send all review based on the assigned recents days.">
                <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
              </Tippy>
            </div>

            <div className="section-child">
              {wpntswebhook.activereview ?
                <div className={`formInput ${wpntswebhook.globalSettings ? 'global-settings-mode' : 'inactive'}`}>
                  <label htmlFor="interval_review">Time Interval for Review response</label>
                  <div className="wpnts-setting">
                    <select
                      name="interval_review"
                      required
                      onChange={handleIntervalReview}
                      value={wpntswebhook.interval_review}
                      className="review-interval"
                    >
                      <option value={60}>1 min interval</option>
                      <option value={180}>3 min</option>
                      <option value={300}>5 min</option>
                      <option value={18000}>5 hours</option>
                      <option value={1800} disabled={!allConditionsMet}>30 min</option>
                      <option value={3600} disabled={!allConditionsMet}>1 hour</option>
                      <option value={36000} disabled={!allConditionsMet}>10 hours</option>
                      <option value={54000} disabled={!allConditionsMet}>15 hours</option>
                      <option value={64800} disabled={!allConditionsMet}>18 hours</option>
                      <option value={86400} disabled={!allConditionsMet}>24 hours</option>
                      <option value={172800} disabled={!allConditionsMet}>2 days</option>
                      <option value={259200} disabled={!allConditionsMet}>3 days</option>
                      <option value={604800} disabled={!allConditionsMet}>7 days</option>
                    </select>
                  </div>
                </div>
                : ''
              }
            </div>
          </div>

        </div>

        <div className="wpnts-switch-support">

          <div className="parent-section">
            <div className="toogle-section">
              <ReactSwitchsupport uncheckedIcon checkedIcon className="supportSwitch-1" name="wpnts-switch-support" id="supportnoti" onChange={handleActivatesupport} checked={wpntswebhook.activesupport} 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="supportnoti">Enable Unresolved Support notification:</label>
              <Tippy content="Send all unresolved support notifications to Slack based on the period and days specified. It will send unresolved tickets at your intervals of choice until they are resolved.">
                <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
              </Tippy>
            </div>

            <div className="section-child">

              {wpntswebhook.activesupport ?
                <div className={`formInput ${wpntswebhook.globalSettings ? 'global-settings-mode' : 'inactive'}`}>
                  <label htmlFor="interval">Time Interval for Support response</label>
                  <div className="wpnts-setting">
                    <select
                      name="interval"
                      required
                      onChange={handleInterval}
                      value={wpntswebhook.interval}
                      className="support-interval"
                    >
                      <option value={60}>1 min interval</option>
                      <option value={180}>3 min</option>
                      <option value={300}>5 min</option>
                      <option value={18000}>5 hours</option>
                      <option value={1800} disabled={!allConditionsMet}>30 min</option>
                      <option value={3600} disabled={!allConditionsMet}>1 hour</option>
                      <option value={36000} disabled={!allConditionsMet}>10 hours</option>
                      <option value={54000} disabled={!allConditionsMet}>15 hours</option>
                      <option value={64800} disabled={!allConditionsMet}>18 hours</option>
                      <option value={86400} disabled={!allConditionsMet}>24 hours</option>
                      <option value={172800} disabled={!allConditionsMet}>2 days</option>
                      <option value={259200} disabled={!allConditionsMet}>3 days</option>
                      <option value={604800} disabled={!allConditionsMet}>7 days</option>
                    </select>
                  </div>
                </div>
                : ''}
            </div>
          </div>

        </div>

        <div className="wpnts-switch-download">
          {/* <p className="NEW_TAG">New</p> */}
          <div className="parent-section">
            <div className="toogle-section">
              <ReactSwitchsupport uncheckedIcon checkedIcon className="supportSwitch-1" name="wpnts-review-hiked" id="review-hiked-info" onChange={handleActivereviewhiked} checked={wpntswebhook.active_review_hiked} 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="review-hiked-info">Enable plugin review status:</label>
              <Tippy content="Send plugin review hiked information. Once its increase or decreased">
                <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
              </Tippy>
            </div>

            {/* <div className="section-child"></div> */}
          </div>

        </div>


        <div className="wpnts-switch-download">
          {/* <p className="NEW_TAG">New</p> */}
          <div className="parent-section">
            <div className="toogle-section">
              <ReactSwitchsupport uncheckedIcon checkedIcon className="supportSwitch-1" name="wpnts-plugin-detail" id="plugin-detail-info" onChange={handleWeeklyPluginInfo} checked={wpntswebhook.plugin_detail_info} 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="plugin-detail-info">Enable weekly plugin overview:</label>
              <Tippy content="Send plugin overview in each week from the time its enabled">
                <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
              </Tippy>
            </div>

            {/* <div className="section-child"></div> */}
          </div>

        </div>


        <div className="wpnts-switch-download">
          {/* <p className="NEW_TAG">New</p> */}
          <div className="parent-section">
            <div className="toogle-section">
              <ReactSwitchsupport uncheckedIcon checkedIcon className="supportSwitch-1" name="wpnts-active-installation" id="active-info-installation" onChange={handleActiveinstallation} checked={wpntswebhook.activeinstallation} 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="active-info-installation">Get information about downloading plugins:</label>
              <Tippy content="Send plugin total downloads each day. How much has been downloaded and how much has increased from the previous.">
                <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
              </Tippy>
            </div>

            {/* <div className="section-child"></div> */}
          </div>

        </div>




        <div className={`wpnts-switch-download`}>
          {!allConditionsMet ? <p className="PRO_TAG">PRO</p> : ''}
          <div className={`wpnts_ispro ${allConditionsMet ? '' : 'inactive'}`}>
            <ReactSwitchsupport uncheckedIcon checkedIcon className="supportSwitch-2" name="wpnts-switch-new-support" id="instantReviewNoti"
              checked={wpntswebhook.activeinstantreview}
              onChange={handleActivateInstantreview}
              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="instantReviewNoti">Enable day to day notification for review:</label>
            <Tippy content="Send only new review notifications in Slack on a daily basis. This will send each new review to Slack once. This update reduces the number of duplicate notifications for same case.">
              <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
            </Tippy>

          </div>
        </div>

        <div className={`wpnts-switch-download`}>
          {!allConditionsMet ? <p className="PRO_TAG">PRO</p> : ''}
          {/* <p className="NEW_TAG">New</p> */}
          <div className={`wpnts_ispro ${allConditionsMet ? '' : 'inactive'}`}>
            <ReactSwitchsupport uncheckedIcon checkedIcon className="supportSwitch-2" name="wpnts-switch-new-support" id="instantSupportNoti"
              checked={wpntswebhook.activeinstantsupport}
              onChange={handleActivateInstantsupport}
              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="instantSupportNoti">Enable day to day notification for support:</label>
            <Tippy content="Send only new support case notifications in Slack on a daily basis. This will send each new created support to Slack once. This update reduces the number of duplicate notifications for same case.">
              <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
            </Tippy>

          </div>
        </div>

        <div className={`wpnts-switch-download`}>
          {!allConditionsMet ? <p className="PRO_TAG">PRO</p> : ''}
          {/* <p className="NEW_TAG">New</p> */}
          <div className={`wpnts_ispro ${allConditionsMet ? '' : 'inactive'}`}>
            <ReactSwitchsupport uncheckedIcon checkedIcon className="supportSwitch-2" name="wpnts-switch-download" id="downloadnoti"
              onChange={handleWeeklydownload}
              checked={wpntswebhook.weeklydownload}
              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="downloadnoti">Enable weekly plugin download notification:</label>
            <Tippy content="Send weekly download report to slack. So it will give you the amount of plugin downloaded each day on a daily basis in every week ">
              <span className="wcs_title"><HelpOutlineIcon className='wcs_tooltip_icon' /></span>
            </Tippy>

          </div>

        </div>

      </div>
      <div className="acb_right">
        <form action="" id="wpntswebhook">

          <div className="formInput global-apis">
            <label htmlFor="useGlobalSettings">Use Global Settings</label>
            <div className="wpnts-setting global-settings-checkbox">
              <input type="checkbox" id="useGlobalSettings" name="useGlobalSettings" onChange={handleUseGlobalSettings} checked={wpntswebhook.globalSettings} />
              <label htmlFor="useGlobalSettings">Check to use global settings</label>
            </div>
          </div>

          {/* Mail  */}
          {/* <div className="formInput global-apis">
            <label htmlFor="authorPaneltoMail">Notification send to Mail</label>
            <div className="wpnts-setting global-settings-checkbox">
              <input type="checkbox" id="authorPaneltoMail" name="authorPaneltoMail" onChange={handleAuthorPaneltoMail} checked={wpntswebhook.authorPaneltoMail} />
              <label htmlFor="authorPaneltoMail">Check to receive notification to Mail</label>
            </div>
          </div> */}

          <div className={`formInput ${wpntswebhook.globalSettings ? 'global-settings-mode' : 'inactive'}`}>
            <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.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>



          {wpntswebhook.activereview || wpntswebhook.activesupport ?
            <div className="formInput">
              <label htmlFor="reviewDays">How recents data you're looking for?</label>
              <div className="wpnts-setting">
                <select
                  name="reviewDays"
                  required
                  onChange={handleIntervalDays}
                  value={wpntswebhook.reviewDays}
                  className="recent-days-interval"
                >

                  <option value={-8}>8 days</option>
                  <option value={-9}>9 days</option>
                  <option value={-10}>10 days</option>
                  <option value={-15}>15 days</option>
                  <option value={-20}>20 days</option>
                  <option value={-60} >Last 2 month</option>
                  <option value={-30} >30 days</option>
                  <option value={-1} disabled={!allConditionsMet}>From last 1 days</option>
                  <option value={-2} disabled={!allConditionsMet}>last 2 days</option>
                  <option value={-3} disabled={!allConditionsMet}>3 days</option>
                  <option value={-4} disabled={!allConditionsMet}>4 days</option>
                  <option value={-5} disabled={!allConditionsMet}>5 days</option>
                  <option value={-7} disabled={!allConditionsMet}>7 days</option>
                </select>
              </div>
            </div>
            : ''}

          <button className="save-webhook" onClick={handleSave}>SAVE</button>
        </form>
      </div>

      {modalOpen && <><div class="wcs_popup_overlay"></div> <Modal setOpenModal={setModalOpen} /> </>}
      <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 Author
