import Cookies from 'js-cookie'
import {callAction} from '../components/http-action';
import {isValidPostcodeField} from '../components/validation';

const wisdomEl = {
    wisdomBlock: '.order-item__wisdom',
    orderItem: '.order-item',
    wisdomBlockHide: 'order-item__wisdom-hide',
    actionBtn: 'order-item__action-btn',
    closeLink: 'order-item__wisdom-link',
    wisdom: '.wisdom',
    wisdomLoggedIn: 'wisdom__logged-in',
    postcodeInput: '.wisdom-postcode',
    notificationBlock: '.wisdom__notification',
    wisdomPartial: 'wisdom__partial',
    wisdomAdded: 'wisdom__added',
    formAdd: '.wisdom__add-form',
    formAddError: 'wisdom__add-form-error',
    quantityField: '.order-item__quantity-value',
    ccOrderInfo: '.cc-order__info',
}

export function checkDeliveryStock(e) {
    e.preventDefault()
    let context = $(this).closest(wisdomEl.orderItem);
    let postcode = context.find(wisdomEl.postcodeInput).val();
    context.find(wisdomEl.notificationBlock).empty();

    if (isValidPostcodeField(postcode)) {
        context.find(wisdomEl.formAdd).removeClass(wisdomEl.formAddError);
        checkAvailability(context, postcode);
        updateCookieValue(postcode);
    } else {
        context.find(wisdomEl.formAdd).addClass(wisdomEl.formAddError);
    }
}

function checkAvailability(context, postcode) {
    let quantity = +context.find(wisdomEl.quantityField).val(),
        productCode = context.find(wisdomEl.ccOrderInfo).attr('data-product'),
        encodedPostcode = encodeURIComponent(postcode);

    if (!Wick.chechLocalEnv) {
        const payload = {
            link: `/delivery-availability?postcode=${encodedPostcode}&productCode=${productCode}&quantity=${quantity}`,
            type: 'GET'
        };
        callAction(payload, getDeliveryAvailability, context, postcode)
    } else {
        //local usage
        getDeliveryAvailability(Wick.BasketData.checkStockBasketResponse, context, postcode);
    }
}

function getDeliveryAvailability(data, context, postcode) {
    const available = data.availableQuantity,
        quantity = +context.find(wisdomEl.quantityField).val();

    context.find(wisdomEl.wisdom).attr('data-available', available);

    Wick.Wisdom.showDefaultStage(event, context);
    if (data.availableArea) {
        if (available > 0) {
            if (available >= quantity) {
                Wick.Wisdom.executeSuccessScenarioPLP_Basket(context, postcode);
            } else {
                Wick.Wisdom.executePartialScenario(context, available, postcode);
            }
        } else {
            Wick.Wisdom.executeErrorScenario(context, postcode);
        }
    } else {
        Wick.Wisdom.executeErrorScenario(context, postcode);
    }
}

export function addDeliveryStock(e) {
    e.preventDefault();
    let context = $(this).closest(wisdomEl.orderItem),
        entryNumber = context.attr('data-id'),
        postcode = context.find(wisdomEl.postcodeInput).val(),
        encodedPostcode = encodeURIComponent(postcode),
        available = +context.find(wisdomEl.wisdom).attr('data-available'),
        quantity;



    if (context.find(wisdomEl.wisdom).hasClass(wisdomEl.wisdomAdded)) {
        quantity = +context.find(wisdomEl.quantityField).val();
    } else if (context.find(wisdomEl.wisdom).hasClass(wisdomEl.wisdomPartial)) {
        quantity = available;
    }

    if (!Wick.chechLocalEnv) {
        const payload = {
            link: `/cart/entry/${entryNumber}/delivery/${encodedPostcode}?quantity=${quantity}`,
            type: 'PUT'
        };
        callAction(payload, addForDelivery);
    } else {
        //local usage
        addForDelivery(Wick.BasketData.wisdomAddForDelivery);
    }
}

function addForDelivery(data) {
    if (data.statusCode === 'success') {
        Wick.BasketPage.showNotification(data)
        Wick.BasketPage.updateCart(true);
    } else {
        Wick.BasketPage.showNotification(data)

    }
}

export function toggleWisdom(e) {
    e.preventDefault()

    if ($(this).hasClass(wisdomEl.actionBtn)) {
        $(this)
            .closest(wisdomEl.orderItem)
            .find(wisdomEl.wisdomBlock)
            .removeClass(wisdomEl.wisdomBlockHide);

        isPostcodePopulated(this)
    } else if ($(this).hasClass(wisdomEl.closeLink)) {
        $(this)
            .closest(wisdomEl.orderItem)
            .find(wisdomEl.wisdomBlock)
            .addClass(wisdomEl.wisdomBlockHide);
    }
}

function isPostcodePopulated(context) {
    const populatedPostcodeField = $('#wisdomPostCode'),
        orderItem = $(context).closest(wisdomEl.orderItem);

    if (populatedPostcodeField.length) {
        const postcode = populatedPostcodeField.val();
        orderItem.find(wisdomEl.postcodeInput).val(postcode);
        checkAvailability(orderItem, postcode);
    }
}

function updateCookieValue(postcode) {
    const cookieId = 'savedSearchWisdom',
        populatedPostcodeField = $('#wisdomPostCode');

    if (populatedPostcodeField.length) {
        populatedPostcodeField.val(postcode);
        Cookies.set(cookieId, postcode);

    }
}

export function createWisdom(item) {
    if (item.cartPageControls.availableForWickesFulfilment) {
        return `
              <section class="order-item__wisdom order-item__wisdom-hide">
                    <div class="order-item__wisdom-close">
                        <a href="#" class="order-item__wisdom-link">
                            Close
                        </a>
                    </div>
                    <div class="wisdom wisdom-basket">
                        <div class="wisdom__notification">
                        </div>
                        <div class="wisdom__change wisdom__change-hide">
                            <a href="#" class="wisdom__link">
                                Change postcode
                            </a>
                        </div>
                        <p class="wisdom__description">
                            <span class="wisdom__description-default">
                               Enter your postcode to check delivery stock in your area
                            </span>
                            <span class="wisdom__description-added">
                               Check stock & add to basket for delivery to:
                            </span>
                            <span class="wisdom__description-partial">
                                A reduced quantity will be added to your basket
                            </span>
                            <span class="wisdom__description-partial-added">
                            </span>
                        </p>
                        <div class="wisdom__add-form">
                            <div class="wisdom__col wisdom__input">
                                <label>
                                    <input type="text" class="tbx wisdom-postcode" value="" id="wisdom-postcode" name="wisdom-postcode" placeholder="">
                                </label>
                            </div>
                            <p class="wisdom__error">
                                Check that you entered a valid postcode.
                            </p>
                            <div class="wisdom__col">
                                <button class="btn btn-primary btn_full wisdom__btn-add">
                                    <span class="btn__text">Add for Delivery</span>
                                    <span class="btn__text-oos">Add for Delivery not available</span>
                                    <span class="btn__text-partial"></span>
                                </button>
                                <button class="btn btn-primary btn_full wisdom__btn-check">
                                    <span class="btn__text">Check</span>
                                </button>
                            </div>
                        </div>
                    </div>
              </section>
            `
    } else {
        return ''
    }

}
