import create from 'zustand';
import { DOMAINS_CART_STORAGE_KEY } from '../constants/actions';
import { getCtaApiEndpoint } from '../tools/urlTools';

const initialState = {
    selectedDomains: [],
    appId: null,
    localStorageRoot: null,
    callToActions: null
};

export const domainAppDataStore = create((set, get) => ({
    ...initialState,
    initializeDomains: appId => set(() => {
        const localStorageRoot = `${DOMAINS_CART_STORAGE_KEY}${appId}`;
        const dataRaw = window.localStorage.getItem(localStorageRoot);
        const selectedDomains = (dataRaw && JSON.parse(dataRaw)) || [];
        return {
            localStorageRoot,
            appId,
            selectedDomains
        };
    }),

    setCallToActions: callToActions => set(() => (
        {
            callToActions
        }
    )),

    addDomain: domain => set(({ selectedDomains }) => {
        const { name } = domain;
        const newData = [
            ...selectedDomains
        ];
        const existingKey = newData.findIndex(item => item.name === name);
        if (existingKey === -1) {
            newData.push(domain);
        } else {
            newData[existingKey] = domain;
        }

        const localStorageKey = get().localStorageRoot;
        window.localStorage.setItem(localStorageKey, JSON.stringify(Object.values(newData)));

        return {
            selectedDomains: newData
        };
    }),

    removeDomain: domain => set(({ selectedDomains }) => {
        const { name } = domain;
        const newData = [
            ...selectedDomains
        ];
        const existingKey = newData.findIndex(item => item.name === name);
        if (existingKey !== -1) {
            newData.splice(existingKey, 1);
        }

        const localStorageKey = get().localStorageRoot;
        window.localStorage.setItem(localStorageKey, JSON.stringify(newData));

        return {
            selectedDomains: newData
        };
    }),

    clearDomains: () => set(() => {
        const { appId, localStorageKey } = get();

        window.localStorage.removeItem(localStorageKey);
        return {
            ...initialState,
            appId
        };
    }),

    handleBuyNowDomains: buyActionType => {
        const { selectedDomains, appId, clearDomains } = get();
        const params = [
            `productId=${appId}`,
            `type=${buyActionType}`,
            ...selectedDomains.map(values => `domain=${values.name},${values.editionPricingUuid}`)
        ].join('&');

        clearDomains();
        const ctaApiEndpoint = getCtaApiEndpoint(params);
        window.location.replace(ctaApiEndpoint);
    },

    handleAddToCartDomains: () => {
        const { selectedDomains, clearDomains } = get();

        if (!selectedDomains) {
            return;
        }

        const domains = selectedDomains.map(({ name, editionPricingUuid }) => (
            {
                name,
                eppid: editionPricingUuid
            }
        ));

        if (window.AD_addToCart) {
            window.AD_addToCart(undefined, undefined, { domains });
            clearDomains();
        }
    }
}));
