const Handlebars = require('hbsfy/runtime');
const markdown = require('helper-markdown');

import { arrayToObjectByIndex } from '../utils/array-utils';

import price from '../../../components/kitchen/price.hbs';
import stripStickers from '../../../components/kitchen/strip-stickers.hbs';
import slide from '../../../components/kitchen/slide.hbs';
import infoIcon from '../../../components/info-icon.hbs';

(function () {
    const CLASSES = {
        activeSwatch: 'colour-swatch--active',
        hiddenSwatch: 'colour-swatch--hidden',
    };

    const SELECTORS = {
        kitchenCardsContainer: '.kitchen-cards',
        cardContainer: '.kitchen-card',
        colourSwatch: '.colour-swatch',
        moreSwatchesButton: '.swatch-more',
        hiddenSwatch: '.colour-swatch--hidden',
        activeSwatch: '.colour-swatch--active',
        swatchesText: '.colour-swatches__text',
        designText: '.kitchen-card__design',
        finishesText: '.kitchen-card__finishes',
        ctaLink: '.kitchen-card__cta a',
        stripsContainer: '.kitchen-card__strips',
        priceContainer: '.kitchen-card__price',
        tooltip: '[data-toggle="tooltip"]',
    };

    let kitchenData = [];

    Handlebars.registerPartial('info-icon', infoIcon);

    Handlebars.registerHelper('markdown', markdown());
    Handlebars.registerHelper('ifCond', function (v1, operator, v2, options) {
        if (operator === '||') {
            return v1 || v2 ? options.fn(this) : options.inverse(this);
        }
    });
    Handlebars.registerHelper('optimizeImageUrl', function (url, width) {
        const queryParameters = `format=pjpg&auto=webp&quality=90&width=${width}`;
        const connectSymbol = url.includes('?') ? '&' : '?';

        return `${url}${connectSymbol}${queryParameters}`;
    });
    Handlebars.registerHelper('formatPrice', function (value) {
        if (typeof value === 'number') {
            return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
        }

        return value;
    });

    function normalizeKitchenData(kitchens) {
        const transformedKitchens = kitchens.map((kitchen) => ({
            ...kitchen,
            colourDatas: arrayToObjectByIndex(kitchen.colourDatas),
        }));

        return arrayToObjectByIndex(transformedKitchens);
    }

    function transformStripStickerDataForHbs(stickers) {
        return stickers.map((sticker) => ({
            text: sticker.text,
            background: sticker.backgroundColour,
            text_colour: sticker.textColour,
        }));
    }

    function transformPriceDataForHbs(priceData) {
        return {
            price: priceData.price,
            was_price: priceData.wasPrice,
            finance_price: priceData.financePrice,
            tooltip_text: priceData.tooltipText,
            additional_text: priceData.additionalText,
            price_offer: priceData.isPriceOffer,
        };
    }

    function updateSwiperView($cardSwiper, images, sticker, pdpUrl) {
        $cardSwiper.removeAllSlides();
        const newSlidesHtml = slide({ images, sticker, pdpUrl });
        $cardSwiper.appendSlide(newSlidesHtml);
        $cardSwiper.slideTo(0, 0);
    }
    function updateSwatchesTextView($cardContainer, colourName) {
        $cardContainer.find(SELECTORS.swatchesText).text(`in ${colourName}`);
    }
    function updateParametersView($cardContainer, design, finishes) {
        const finishesText = finishes.join(', ');
        const finishesLabel = finishes.length > 1 ? 'finishes' : 'finish';

        $cardContainer.find(SELECTORS.designText).text(`${design} design`);
        $cardContainer.find(SELECTORS.finishesText).text(`${finishesText} ${finishesLabel}`);
    }
    function updateCTALink($cardContainer, url) {
        $cardContainer.find(SELECTORS.ctaLink).attr('href', url);
    }
    function updateStickersView($cardContainer, stickersData) {
        const updatedStickersData = transformStripStickerDataForHbs(stickersData);
        const newStripStickersHtml = stripStickers({ strip_stickers: updatedStickersData });

        $cardContainer.find(SELECTORS.stripsContainer).html(newStripStickersHtml);
    }

    function updatePriceView($cardContainer, priceData) {
        const updatedPriceData = transformPriceDataForHbs(priceData);
        const newPriceHtml = price({ price: updatedPriceData, small: true });

        $cardContainer.find(SELECTORS.priceContainer).html(newPriceHtml);
        $cardContainer.find(SELECTORS.tooltip).tooltip();
    }

    function handleMoreSwatchesClick() {
        const $button = $(this);
        $button.siblings(SELECTORS.hiddenSwatch).removeClass(CLASSES.hiddenSwatch);
        $button.hide();
        $(window).trigger('kitchenCardChanged');
    }

    function handleColourSwatchClick() {
        const $swatch = $(this);
        const $cardContainer = $swatch.closest(SELECTORS.cardContainer);
        const $currentSwatchActive = $swatch.siblings(SELECTORS.activeSwatch);

        const colourId = $swatch.data('id');
        const kitchenId = $cardContainer.data('id');

        const currentKitchenData = kitchenData[kitchenId];
        const colourData = currentKitchenData.colourDatas[colourId];

        const $cardSwiper = Wick.PLPCardSwiper[kitchenId];

        updatePriceView($cardContainer, colourData.priceData);
        updateStickersView($cardContainer, colourData.stickers);
        updateSwatchesTextView($cardContainer, colourData.colourSwatch.colourName);
        updateSwiperView(
            $cardSwiper,
            colourData.images,
            currentKitchenData.rangeStickers[0],
            colourData.pdpUrl
        );
        updateParametersView($cardContainer, colourData.design, colourData.finishes);
        updateCTALink($cardContainer, colourData.pdpUrl);

        $currentSwatchActive.removeClass(CLASSES.activeSwatch);
        $swatch.addClass(CLASSES.activeSwatch);
        $(window).trigger('kitchenCardChanged');
    }

    function initKitchenPLP(_, PLPKitchenData) {
        const $kitchenCardsContainer = $(SELECTORS.kitchenCardsContainer);

        kitchenData = normalizeKitchenData(PLPKitchenData);

        $kitchenCardsContainer.on('click', SELECTORS.colourSwatch, handleColourSwatchClick);
        $kitchenCardsContainer.on('click', SELECTORS.moreSwatchesButton, handleMoreSwatchesClick);
    }

    $(document).ready(function () {
        $(document).on('initKitchenPLP', initKitchenPLP);
    });
})();
