import Switch from "react-switch";
import { Bars } from  'react-loader-spinner';
import Popup from 'reactjs-popup';
import "../js-css/script.js";

jQuery(document).ready( () => {
    const { render, useState, useEffect } = wp.element;

    function getWebsiteStatusMessage(websiteStatus) {
        let statusMessage = "";
        if (websiteStatus === Mondiad.STATUS_PENDING) {
            statusMessage = "Website is on PENDING status. Wait for website approving.";
        }
        if (websiteStatus === Mondiad.STATUS_REJECTED) {
            statusMessage = "Website is on REJECTED status. Please, select another website.";
        }
        if (websiteStatus === Mondiad.STATUS_DELETED) {
            statusMessage = "Website is deleted. Please, select another website.";
        }
        if (websiteStatus === Mondiad.STATUS_HELD) {
            statusMessage = "Website is on HELD status. Please, check your email for more details or contact the Mondiad support team.";
        }
        return statusMessage;
    }

    const RadioButton = ({label, value, onClick}) => {
        return (
            <label>
                <input type="radio" checked={value} onClick={onClick}/>
                {label}
            </label>
        );
    };

    const Checkbox = ({label, value, onClick}) => {
        return (
            <label className='mondiad-checkbox-label'>
                <input type="checkbox" className='mondiad-checkbox' checked={value} onClick={onClick}/>
                {label}
            </label>
        );
    };

    const StyledLoader = ({isLoading, color}) => {
        return (
            <div className="mondiad-loader">
                <Bars
                    height="20"
                    width="30"
                    color={color ? color : "#51c51d"}
                    ariaLabel="bars-loading"
                    visible={isLoading}
                />
            </div>
        );
    }

    const StyledSwitch = ({switchState, setSwitchState}) => {
        const enabledMessage = "Turn off to hide this type of ads on all your website pages.";
        const disabledMessage = "Turn on to activate this type of ads on all your website pages.";
        const [previousState, setPreviousState] = useState(null);

        const updateSwitchState = (value) => {
            setPreviousState(switchState);
            setSwitchState(value);
        }
        return (
            <div>
                <Switch
                    checked={switchState}
                    onChange={updateSwitchState}
                    onColor="#2693e6"
                    onHandleColor="#FFFFFF"
                    offColor="#BFBFBF"
                    offHandleColor="#FFFFFF"
                    handleDiameter={18}
                    boxShadow="0px 1px 5px rgba(0, 0, 0, 0.6)"
                    height={22}
                    width={90}
                    className="mondiad-switch"
                    uncheckedIcon={
                        <div style={{
                            fontSize: "13px",
                            color: "#FFFFFF",
                            position: "relative",
                            left: "-31px",
                            top: "2px"
                        }}>
                            Disabled
                        </div>
                    }
                    checkedIcon={
                        <div style={{
                            fontSize: "13px",
                            color: "#FFFFFF",
                            position: "relative",
                            left: "12px",
                            top: "2px"
                        }}>
                            Enabled
                        </div>
                    }
                />
                <StyledLoader isLoading={previousState === switchState}/>
                <p className='mondiad-table-switch-info'>{switchState ? enabledMessage : disabledMessage}</p>
            </div>
        )
    }

    const TextField = ({
                           label,
                           inputName = null,
                           isRequired = false,
                           type = 'text',
                           value = '',
                           inputId = null,
                           additionalStyles = '',
                           placeholder = '',
                           onChange = () => {
                           }
                       }) => {
        if (inputId === null) {
            inputId = inputName;
        }
        return (
            <div className={'mondiad-form-field ' + additionalStyles}>
                <label htmlFor={inputId} className='mondiad-field-name'>{label}</label>
                <input className='mondiad-field-input' required={isRequired} type={type} name={inputName} id={inputId}
                       value={value} onChange={onChange} placeholder={placeholder}/>
            </div>
        );
    };

    const WebsiteRow = ({obj}) => {
        const [isLoading, setIsLoading] = useState(false);
        const selectWebsite = () => {
            setIsLoading(true);
            Mondiad.selectSite(obj.id)
        };
        return (
            <tr>
                <td>{obj.id}</td>
                <td>{obj.name}</td>
                <td>{obj.status.toLowerCase()}</td>
                <td>{obj.category}</td>
                <td>{obj.websiteCategory}</td>
                <td>{obj.zonesNumber}</td>
                <td>
                    <RadioButton value={false} onClick={selectWebsite}/>
                    <StyledLoader isLoading={isLoading}/>
                </td>
            </tr>
        );
    }

    const Websites = () => {
        const [data, setData] = useState([]);
        const [filterStr, setFilterStr] = useState(window.location.hostname);
        const [isLoading, setIsLoading] = useState(false);
        const errorCallback = () => {
            setIsLoading(false);
        }
        const successCallback = (list) => {
            setData(list);
            setIsLoading(false)
        }
        const loadData = (name) => {
            setFilterStr(name);
            setIsLoading(true);
            Mondiad.searchSite(name, successCallback, errorCallback);
        }
        useEffect(() => {
          loadData(filterStr);
        }, []);
        return (
            <div>
                <p className='mondiad-info'>
                    Select one of the existing websites or create a new one.
                </p>

                <div className='mondiad-search-loader'><StyledLoader isLoading={isLoading}/></div>
                <TextField label='Search website by domain' value={filterStr} placeholder='Enter website domain'
                           onChange={e => loadData(e.target.value)}/>
                <table className='mondiad-table mondiad-table-scrollable'>
                    <thead>
                    <tr>
                        <th>Id</th>
                        <th>Domain name</th>
                        <th>Status</th>
                        <th>Category</th>
                        <th>Type</th>
                        <th>Zones</th>
                        <th>Use site</th>
                    </tr>
                    </thead>
                    <tbody>
                    {data.map((object, i) => <WebsiteRow obj={object}/>)}
                    </tbody>
                </table>
            </div>
        );
    };

    const isWebsitePage = !!MONDIAD_PHP_VAR.websites_page;
    if (isWebsitePage) {
        render(<Websites/>, document.getElementById('mondiad_website_table_react'));
    }


    const AdRow = ({obj, selectedId, updateDefaultId}) => {
        const isSelected = selectedId == obj.id;
        const [isLoading, setIsLoading] = useState(false);
        const selectAd = () => {
            if (isSelected)
                return;
            setIsLoading(true);
            updateDefaultId(obj.id, obj.adZoneUuidId, () => {
                setIsLoading(false)
            })
        };
        const statusColor = obj.status === Mondiad.AD_STATUS_ACTIVE ? 'mondiad-lightgreen' : '';

        return (
            <tr>
                <td>{obj.id}</td>
                <td>{obj.name}</td>
                <td className={statusColor}>{obj.status.toLowerCase()}</td>
                <td>{obj.createDate.split('T')[0]}</td>
                <td>
                    <RadioButton value={isSelected} onClick={selectAd}/>
                    <StyledLoader isLoading={isLoading}/>
                </td>
            </tr>
        );
    }

    const AdRowNativeOrBanner = ({obj}) => {
        const statusColor = obj.status === Mondiad.AD_STATUS_ACTIVE ? 'mondiad-lightgreen' : '';

        return (
            <tr>
                <td>{obj.id}</td>
                <td>{obj.name}</td>
                <td className={statusColor}>{obj.status.toLowerCase()}</td>
                <td>{obj.createDate.split('T')[0]}</td>
            </tr>
        );
    }

    const AdTable = ({
                         data,
                         RenderRowFn,
                         switchDefaultState,
                         switchRequestFn,
                         defaultSelectedId = null,
                         title,
                         tableHeaders,
                         setDefaultIdRequestFn = null
                     }) => {
        const [switchState, setSwitchState] = useState(switchDefaultState);
        const [selectedId, updateId] = useState(defaultSelectedId);
        const updateActivity = () => {
            switchRequestFn(setSwitchState)
        }
        const updateDefaultId = (id, uuid, callback) => {
            setDefaultIdRequestFn(id, uuid, () => {
                updateId(id);
                callback();
            })
        }
        return (
            <div className='mondiad-table-with-title'>
                <div className='mondiad-table-title-box'>
                    <p className='mondiad-table-title'>{title}</p>
                </div>
                <div className='mondiad-table-with-switch'>
                    <StyledSwitch switchState={switchState} setSwitchState={updateActivity}/>
                    {switchState ?
                        <table className='mondiad-table'>
                            <thead>
                            <tr>
                                {tableHeaders.map((name, i) => <th>{name}</th>)}
                            </tr>
                            </thead>
                            <tbody>
                            {Object.entries(data).map(
                                (object, i) => <RenderRowFn obj={object[1]} selectedId={selectedId}
                                                            updateDefaultId={updateDefaultId}/>
                            )}
                            </tbody>
                        </table>
                        : null
                    }
                </div>
            </div>
        );
    }

    const Ads = () => {
        const websiteName = MONDIAD_PHP_VAR.website_name;
        const websiteStatus = MONDIAD_PHP_VAR.website_status;

        const defaultClassicId = MONDIAD_PHP_VAR.ads_classic_default;
        const defaultInpageId = MONDIAD_PHP_VAR.ads_inpage_default;

        const isInpageEnabled = MONDIAD_PHP_VAR.ads_inpage_enabled;
        const isClassicEnabled = MONDIAD_PHP_VAR.ads_classic_enabled;
        const isNativeEnabled = MONDIAD_PHP_VAR.ads_native_enabled;
        const isBannerEnabled = MONDIAD_PHP_VAR.ads_banner_enabled;

        const data = MONDIAD_PHP_VAR.ads_list;
        const native = data.NATIVE;
        const inpage = data.IN_PAGE_PUSH;
        const classic = data.CLASSIC_PUSH;
        const banner = data.BANNER;

        const statusMessage = getWebsiteStatusMessage(websiteStatus);

        return (
            <div>
                <div className='mondiad-website-info'>
                    <p className='mondiad-website-name mondiad-lightgreen'>{websiteName}</p>
                    {statusMessage ? <p className='mondiad-info'>{statusMessage}</p> : null}
                </div>
                {inpage ?
                    <div className='mondiad-zone-part mondiad-ad-table'>
                        <AdTable
                            data={inpage}
                            RenderRowFn={AdRow}
                            defaultSelectedId={defaultInpageId}
                            title='In-Page Push'
                            switchRequestFn={Mondiad.toggleInpageEnabled}
                            switchDefaultState={isInpageEnabled}
                            tableHeaders={['ID', 'Name', 'Status', 'Created Date', 'Use as default']}
                            setDefaultIdRequestFn={Mondiad.selectDefaultInpage}
                        />
                    </div>
                    : null
                }
                {classic ?
                    <div className='mondiad-zone-part mondiad-ad-table'>
                        <AdTable
                            data={classic}
                            RenderRowFn={AdRow}
                            defaultSelectedId={defaultClassicId}
                            title='Classic Push'
                            switchRequestFn={Mondiad.toggleClassicEnabled}
                            switchDefaultState={isClassicEnabled}
                            tableHeaders={['ID', 'Name', 'Status', 'Created Date', 'Use as default']}
                            setDefaultIdRequestFn={Mondiad.selectDefaultClassic}
                        />
                    </div>
                    : null
                }
                {native ?
                    <div className='mondiad-zone-part mondiad-ad-table-native'>
                        <AdTable
                            data={native}
                            RenderRowFn={AdRowNativeOrBanner}
                            title='Native'
                            switchRequestFn={Mondiad.toggleNativeEnabled}
                            switchDefaultState={isNativeEnabled}
                            tableHeaders={['ID', 'Name', 'Status', 'Created Date']}
                        />
                    </div>
                    : null
                }
              {banner ?
                  <div className='mondiad-zone-part mondiad-ad-table-banner'>
                    <AdTable
                      data={banner}
                      RenderRowFn={AdRowNativeOrBanner}
                      title='Banners'
                      switchRequestFn={Mondiad.toggleBannerEnabled}
                      switchDefaultState={isBannerEnabled}
                      tableHeaders={['ID', 'Name', 'Status', 'Created Date']}
                    />
                  </div>
                  : null
                }
                {!inpage && !classic && !native && !banner ?
                    <p>Website doesn't have any adzone</p>
                    : null
                }
            </div>
        )
    };

    const isAdsPage = !!MONDIAD_PHP_VAR.ads_page;
    if (isAdsPage) {
        render(<Ads/>, document.getElementById('mondiad_ads_table_react'));
    }

    const DropDown = ({initialState, label, selectName, list}) => {
        const [currentItem, setCurrentItem] = useState(initialState);
        return (
            <div>
                <label className='mondiad-metabox-ad-select-label'>{label}</label>
                <select className='mondiad-metabox-ad-select' name={selectName} id={selectName} value={currentItem}
                        onChange={e => setCurrentItem(e.target.value)}>
                    <option value="">--default--</option>
                    <option value={Mondiad.METABOX_AD_DISABLED}>--disabled--</option>
                    {Object.entries(list).map((ad, i) => <option value={ad[1].id}>{ad[1].name}</option>)}
                </select>
            </div>
        );
    }

    const MetaNativePopup = ({list}) => {
        const onClick = (e) => {
            Mondiad.copy(e.target);
        };
        return (
            <div>
                <label className='mondiad-metabox-ad-select-label'>Native</label>
                <Popup trigger={<input type='button' className='mondiad-metabox-trigger' value="Select shortcode"/>}
                       position="top right">
                    {close => (
                        <div>
                            <span>Click code tag to copy it's value</span>
                            <ul>
                                {Object.entries(list).map((ad, i) =>
                                    <li>
                                        <div>{ad[1].name}</div>
                                        <div><code className='mondiad-copy' onClick={onClick}>[mondiad-native-ad
                                            uuid='{ad[1].adZoneUuidId}']</code></div>
                                    </li>
                                )}
                            </ul>
                        </div>
                    )}
                </Popup>
            </div>
        );
    }

    const MetaBannerPopup = ({list}) => {
      const onClick = (e) => {
        Mondiad.copy(e.target);
      };
      return (
        <div>
          <label className='mondiad-metabox-ad-select-label'>Banners</label>
          <Popup trigger={<input type='button' className='mondiad-metabox-trigger' value="Select shortcode"/>}
                 position="top right">
            {close => (
              <div>
                <span>Click code tag to copy it's value</span>
                <ul>
                  {Object.entries(list).map((ad, i) =>
                    <li>
                      <div>{ad[1].name}</div>
                      <div><code className='mondiad-copy' onClick={onClick}>[mondiad-banner-ad
                        uuid='{ad[1].adZoneUuidId}']</code></div>
                    </li>
                  )}
                </ul>
              </div>
            )}
          </Popup>
        </div>
      );
    }

    const MetaBox = () => {
        const data = MONDIAD_PHP_VAR.meta_box_data;
        const initialInpage = MONDIAD_PHP_VAR.metabox_initial_inpage;
        const initialClassic = MONDIAD_PHP_VAR.metabox_initial_classic;
        const isBlockEditor = MONDIAD_PHP_VAR.metabox_is_block_editor;
        const websiteStatus = MONDIAD_PHP_VAR.website_status;

        const native = data.NATIVE;
        const banner = data.BANNER;
        const inpage = data.IN_PAGE_PUSH;
        const classic = data.CLASSIC_PUSH;

        const statusMessage = getWebsiteStatusMessage(websiteStatus);
        return (
            <div>
                <div className='mondiad-info'>{statusMessage}</div>
                <div className='mondiad-metabox-select-group'>
                    {inpage ?
                        <DropDown initialState={initialInpage} label="In-Page Push" list={inpage}
                                  selectName={Mondiad.METABOX_INPAGE_ID}/>
                        : null
                    }
                    {classic ?
                        <DropDown initialState={initialClassic} label="Classic Push" list={classic}
                                  selectName={Mondiad.METABOX_CLASSIC_ID}/>
                        : null
                    }
                    {native ?
                        <MetaNativePopup list={native}/>
                        : null
                    }
                    {banner ?
                      <MetaBannerPopup list={banner}/>
                      : null
                    }
                </div>
                {isBlockEditor ?
                    <p>As you use Block Editor, you can insert native or banner Ad component via Add Block button</p> : null}
            </div>
        );
    };

    const isMetaBox = !!MONDIAD_PHP_VAR.meta_box_data;
    if (isMetaBox) {
        render(<MetaBox/>, document.getElementById('mondiad_meta_box_react'));
    }

    const Login = () => {
        const settingsUrl = MONDIAD_PHP_VAR.settings_url;
        const signUpUrl = MONDIAD_PHP_VAR.sign_up_url;
        const [login, setLogin] = useState("");
        const [pass, setPass] = useState("");
        const [isLoading, setLoading] = useState(false);
        const errorCallBack = () => {
            setLoading(false);
        }
        const makeRequest = () => {
            setLoading(true);
            Mondiad.login(login, pass, errorCallBack)
        };

        return (
            <div>
                <div className='mondiad-info'>
                    <b>How to authorize:</b>
                    <ul>
                        <li>Log into Mondiad publisher management panel</li>
                        <li>Go to <a href={settingsUrl} target='_blank'>Settings -> API integration section</a></li>
                        <li>Generate your API key</li>
                    </ul>
                    <b>If you don't have a Mondiad account, <a href={signUpUrl} target='_blank'>sign up here</a>.</b>
                </div>
                <div className='mondiad-form login'>
                    <TextField label='Client ID' value={login} onChange={e => setLogin(e.target.value)}/>
                    <TextField label='Client Secret' value={pass} onChange={e => setPass(e.target.value)}/>
                    <button type='submit' onClick={makeRequest}>Submit <StyledLoader isLoading={isLoading} color="#fff"/></button>
                </div>
            </div>
        );
    };

    const isLoginPage = !!MONDIAD_PHP_VAR.login_page;
    if (isLoginPage) {
        render(<Login/>, document.getElementById('mondiad_login_react'));
    }

    const Settings = () => {
        const currentDomain = MONDIAD_PHP_VAR.current_domain;
        const redirectUrl = MONDIAD_PHP_VAR.redirect_url;
        const [isLoadingSite, setLoadingSite] = useState(false);
        const [isLoadingLogout, setLoadingLogout] = useState(false);
        const [cleanData, setCleanData] = useState(false);
        const successCallback = () => {
            window.location = redirectUrl;
        }
        const changeWebsiteError = () => {
            setLoadingSite(false);
        }
        const changeWebsite = () => {
            setLoadingSite(true);
            Mondiad.changeWebsite(successCallback, changeWebsiteError)
        };
        const logoutError = () => {
            setLoadingLogout(false);
        }
        const logout = () => {
            setLoadingLogout(true);
            Mondiad.logout(cleanData, successCallback, logoutError)
        }
        return (
            <div>
                {currentDomain ?
                    <div className='mondiad-info'>
                        <p>
                            You are currently using <span className='mondiad-highlight'>{currentDomain}</span> as
                            your website. To change it, click on the "Change website" button.
                        </p>

                        <button type='submit' className='mondiad-button mondiad-short-button' onClick={changeWebsite}>
                            Change site <StyledLoader isLoading={isLoadingSite} color="#fff"/>
                        </button>
                        <p className='mondiad-warning'>
                            WARNING! All Advertising will be removed form all site pages!
                        </p>
                    </div>
                    : null
                }
                <div className='mondiad-info'>
                    <p>
                        To use this plugin with another account, check the "Clean data" box.
                    </p>
                    <div className='mondiad-form-field'>
                        <Checkbox value={cleanData} label="Clean data" onClick={(e) => setCleanData(e.target.checked)}></Checkbox>
                    </div>
                    <button type='submit' className='mondiad-button mondiad-short-button' onClick={logout}>
                        Logout <StyledLoader isLoading={isLoadingLogout} color="#fff"/>
                    </button>
                    {cleanData ?
                        <p className='mondiad-warning'>WARNING! All Advertising will be removed form all site pages!</p>
                        : null
                    }
                </div>
            </div>
        )
    };

    const isSettingsPage = !!MONDIAD_PHP_VAR.settings_page;
    if (isSettingsPage) {
        render(<Settings/>, document.getElementById('mondiad_settings_react'));
    }
})