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

const wisdomEl = {
        wisdomBlock: '.order-item__wisdom',
        orderItem: '.order-item',
        wisdomBlockHide: 'order-item__wisdom-hide',
        actionBtn: 'order-item__action',
        actionBtnElement: '.order-item__action',
        actionCCBtn: '.order-item__action[data-type="Click & Collect"]',
        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',
        formError: '.wisdom__error',
        quantityField: '.order-item__quantity-value',
        ccOrderInfo: '.cc-order__info',
        ccSection: '.cc-order',
    }
const errorStatus = {
    cannotDeliveryToArea: "Sorry, we can't deliver to your area",
    checkValidPostcode: "Please enter a valid postcode",
};
const MINIMUM_FORMATTED_POST_CODE_LENGTH = 3;


export function checkDeliveryStock(e, inputField) {
    e.preventDefault();
    let context = inputField ? $(inputField).closest(wisdomEl.orderItem) : $(this).closest(wisdomEl.orderItem);
    let postcode = context.find(wisdomEl.postcodeInput).val();

    context.find(wisdomEl.notificationBlock).empty();
    if (postcode && isValidPostcodeField(postcode)) {
        context.find(wisdomEl.formAdd).removeClass(wisdomEl.formAddError);
        checkAvailability(context, postcode);
        updateCookieValue(postcode);
    } else {
        showFormError(context, errorStatus.checkValidPostcode);
    }
}

export function checkDeliveryStockOnEnter(e) {
    let keycode = (event.keyCode ? event.keyCode : event.which);
    keycode === 13 && checkDeliveryStock(e, this);
}

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

    context.closest(wisdomEl.orderItem).find(wisdomEl.actionBtnElement).addClass('disabled');

    if (!Wick.checkLocalEnv) {
        const payload = {
            url: ROUTES.WISDOM_CHECK_AVAILABILITY,
            queries: {
                postcode: encodedPostcode,
                productCode: productCode,
                quantity: quantity,
            },
            type: 'GET'
        };
        callAction(payload, getDeliveryAvailability, context, prettifiedPostcode, isPostcodePrePopulated)
    } else {
        getDeliveryAvailability(Wick.BasketData.checkStockBasketResponse, context, prettifiedPostcode, isPostcodePrePopulated);
    }
}

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

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

    Wick.Wisdom.showDefaultStage(context);

    context.find(wisdomEl.formAdd).removeClass(wisdomEl.formAddError);

    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);
            context.find(wisdomEl.postcodeInput).val(postcode);
        }
    } else {
        showFormError(context, errorStatus.cannotDeliveryToArea);
        context.find(wisdomEl.postcodeInput).val(postcode);
    }

    isPostcodePrePopulated && wisdomBlock.removeClass(wisdomEl.wisdomBlockHide);
    context.closest(wisdomEl.orderItem).find(wisdomEl.actionBtnElement).removeClass('disabled');
}

export function addDeliveryStock(e) {
    e.preventDefault();
    let context = $(this).closest(wisdomEl.orderItem),
        entryNumber = context.attr('data-id'),
        prePopulatedPostcode = $('#wisdomPostCode'),
        isPostCodePrePopulated = prePopulatedPostcode.length && prePopulatedPostcode.val().length,
        postcode = isPostCodePrePopulated ? prePopulatedPostcode.val() : 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.checkLocalEnv) {
        const payload = {
            url: `${ROUTES.BASKET_ADD_STOCK}/${entryNumber}/delivery/${encodedPostcode}`,
            queries: {
                quantity: quantity,
            },
            type: 'PUT'
        };
        callAction(payload, addForDelivery);
    } else {
        addForDelivery(Wick.BasketData.wisdomAddForDelivery);
    }
}

function addForDelivery(data) {
    Wick.BasketPage.showNotification(data);
    const statusCode = ['success', 'noStock', 'lowStock', 'maxOrderQuantityExceeded']

    if (statusCode.includes(data.statusCode)) {
        Wick.BasketPage.updateCart(true);
    }
}

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

    const context = $(this).closest(wisdomEl.orderItem),
        wisdomBlock = context.find(wisdomEl.wisdomBlock),
        cc = context.find(Wick.BasketPage.el.ccSection);

    wisdomBlock.find(wisdomEl.formAdd).removeClass(wisdomEl.formAddError);

    if ($(this).hasClass(wisdomEl.actionBtn)) {
        if (wisdomBlock.hasClass(wisdomEl.wisdomBlockHide)) {
            isPostcodePopulated(this);
        }
        Wick.BasketPage.makeRadioActive(this);
        //hide C&C if exist
        cc.length && cc.hide();
    } else if ($(this).hasClass(wisdomEl.closeLink)) {
        wisdomBlock.addClass(wisdomEl.wisdomBlockHide);
        //show C&C if exist
        cc.length && cc.show()
        Wick.BasketPage.makeRadioActive(context.find(wisdomEl.actionCCBtn));
    }
}

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

    if (populatedPostcodeField.length && postcode.length) {
        checkAvailability(orderItem, postcode, true);
    } else {
        wisdomBlock.removeClass(wisdomEl.wisdomBlockHide);
    }
}

function showFormError(context, message) {
    context.find(wisdomEl.formAdd).addClass(wisdomEl.formAddError);
    context.find(wisdomEl.formError).text(message);
}

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

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

export function createWisdom(item) {
    if (item.orderFulfilmentControls.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>
                        <form 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>
                        </form>
                    </div>
              </section>
            `
    } else {
        return ''
    }

}

export function changeWisdomWhenQuantityUpdated(_, context) {
    const cc = context.find(Wick.BasketPage.el.ccSection);
    const wisdomBlock = context.find(wisdomEl.wisdomBlock);
    const actionCCBtn = context.find(wisdomEl.actionCCBtn);
    const productCode = context.find(wisdomEl.ccOrderInfo).attr('data-product');
    const productEntrie = Wick.BasketPage.cartEntries.find(entry => entry?.product?.code === productCode);

    if (wisdomBlock.length && productEntrie?.deliveryPointOfService) {
        cc.length && cc.show();
        Wick.BasketPage.makeRadioActive(actionCCBtn);
        wisdomBlock.addClass(wisdomEl.wisdomBlockHide);
        Wick.Wisdom.showDefaultStage(context);
    }
}

export function transformPostcodeToCanonicalView(postcode = '') {
    const upperCasePostcodeWithoutSpaces = postcode.toUpperCase().replace(/\s/g, '');
    if (upperCasePostcodeWithoutSpaces.length >= MINIMUM_FORMATTED_POST_CODE_LENGTH) {
        return insertSpaceBeforeLastThreeCharacters(upperCasePostcodeWithoutSpaces);
    }
    return upperCasePostcodeWithoutSpaces;
}

function insertSpaceBeforeLastThreeCharacters(postcode = '') {
    const dividerIndex = postcode.length - MINIMUM_FORMATTED_POST_CODE_LENGTH;
    const firstPostcodePart = postcode.substring(0, dividerIndex);
    const secondPostcodePart = postcode.substring(dividerIndex);

    return `${firstPostcodePart} ${secondPostcodePart}`;
}

export function prettifyWisdomPostcode(e) {
    const targetPostcode = $(e.target);
    const postcode = targetPostcode.val();
    const prettifiedPostcode = transformPostcodeToCanonicalView(postcode);
    $(wisdomEl.postcodeInput).val(prettifiedPostcode);
}
