import {
    downscaleImageQuality,
    setTemporaryVisualImage,
    storeImageToIndexedDb
} from '../../autocomplete/features/visual-similarity-search/visual-similarity-search.js';

import {
    athenaConfig,
    athenaConfigOptions
} from '../../global/athena-config.js';

export const findVisuallySimilar = () =>
{
    const imageUrlToBase64ViaImg = (url, format = 'image/png', quality = 0.92) =>
    {
        return new Promise((resolve, reject) => {
            const img = new Image();
            img.crossOrigin = 'anonymous';
            img.src = url;

            img.onload = () => {
                try {
                    const canvas = document.createElement('canvas');
                    canvas.width = img.naturalWidth;
                    canvas.height = img.naturalHeight;

                    const ctx = canvas.getContext('2d');
                    ctx.drawImage(img, 0, 0);

                    const base64 = canvas.toDataURL(format, quality);
                    resolve(base64);
                } catch (err) {
                    reject(err);
                }
            };

            img.onerror = (err) => {
                reject(new Error('Image load failed: ' + err));
            };
        });
    };

    const getProductItem = (target) =>
        target.closest('.product-item') ||
        target.closest('.athena-product-item');

    const getImageSrc = (productItem) =>
        productItem?.querySelector('.athena-product-image-photo')?.src ||
        productItem?.querySelector('.athena-autocomplete__image-product')?.src ||
        null;

    const getSku = (productItem) =>
        productItem?.getAttribute('data-element-sku-autocomplete') ||
        productItem?.getAttribute('data-element-sku-product-recommendation') ||
        productItem?.getAttribute('data-element-sku-search') ||
        null;

    const redirectToForm = (imageKey, sku) => {
        const base = athenaConfig.formUrl.startsWith('http')
            ? athenaConfig.formUrl
            : `${window.location.origin}${athenaConfig.formUrl}`;

        const url = new URL(base);

        url.searchParams.set('image', imageKey);
        url.searchParams.set('conversion-channel', 'similar-style');

        if (sku) {
            url.searchParams.set('clicked_product_sku', sku);
        }

        window.location.href = url.toString();
    };

    const toggleVisuallySimilar = async (
        imageSrc,
        sku
    ) =>
    {
        const base64String = await imageUrlToBase64ViaImg(imageSrc);
        if (!base64String) {
            redirectToForm('', sku);
        }

        downscaleImageQuality(
            base64String,
            athenaConfigOptions.imageQuality,
            async (result) => {

                await setTemporaryVisualImage(result);
                await storeImageToIndexedDb(false, result);

                const keyImage = await storeImageToIndexedDb(true, null, base64String);

                redirectToForm(keyImage, sku);
            }
        );
    }

    document.addEventListener('click', async (event) => {
        const button = event.target.closest('.find-visual-similar');
        if (!button) return;

        event.preventDefault();

        const productItem = getProductItem(button);
        if (!productItem) return;

        const imageSrc = getImageSrc(productItem);
        if (!imageSrc) return;

        const sku = getSku(productItem);

        await toggleVisuallySimilar(imageSrc, sku);
    });

    window.addEventListener('ai-chat-find-visually-similar', async (event) => {
        const {
            imageSrc,
            productSku: sku
        } = event?.detail;

        await toggleVisuallySimilar(imageSrc, sku);
    });
};