import $j from './lib/jquery';
import FreyaSyncService from './freya-sync-service';
import { ToppingData } from './types/topping-data';

export default class ToppingDisplay {
    private static instance: ToppingDisplay;

    private readonly productId?: number;
    private toppings: ToppingData[] = [];
    private productPrice: number = 0;
    private activeToppings: Array<ToppingData> = [];

    private constructor() {
        const id = $j('#FS_TOPPING_PARENT_ID').attr('data-id');
        if (!id) {
            return;
        }
        this.productId = Number(id);
        this.fetchToppings();
    }

    public static bootstrap() {
        if (this.instance) {
            return;
        }

        this.instance = new ToppingDisplay();
    }

    public static get sharedInstance() {
        if (!this.instance) {
            throw new Error('No ToppingDisplay shared instance');
        }

        return this.instance;
    }

    private fetchToppings() {
        if (!this.productId) {
            return;
        }

        $j.ajax({
            url: FreyaSyncService.sharedInstance.data.ajax_url,
            dataType: 'json',
            method: 'GET',
            data: { action: 'fss_get_toppings', id: this.productId, nonce: FreyaSyncService.sharedInstance.data.nonce },
            success: (res: { data: { productPrice: number; toppings: Array<ToppingData> }; success: boolean }) => {
                this.toppings = res.data.toppings;
                this.productPrice = Number(res.data.productPrice);
                this.toggleToppings();
            },
            error: (jqXHR) => {
                console.log(jqXHR.responseJSON);
            },
        });
    }

    private toggleToppings() {
        if (this.toppings.length === 0) {
            return;
        }
        this.toppings.forEach((topping) => {
            this.toggleToppingFromCheckbox(topping.freyaCode, false);
            $j(`#checkbox-${topping.freyaCode}`).on('click', () => {
                this.toggleToppingFromCheckbox(topping.freyaCode, true);
            });
        });
        this.updateToppingPrice();
    }

    private setToppingAsActive(freyaCode: string) {
        const topping = this.toppings.find((topping) => topping.freyaCode === freyaCode);

        if (this.activeToppings.find((topping) => topping.freyaCode === freyaCode)) {
            return;
        }

        if (topping) {
            this.activeToppings.push(topping);
        }
    }

    private disableTopping(freyaCode: string) {
        this.activeToppings = this.activeToppings.filter((topping) => topping.freyaCode !== freyaCode);
    }

    private updateToppingPrice() {
        let price = this.productPrice;
        this.activeToppings.forEach((topping) => {
            price += topping.price;
        });
        if (price === this.productPrice) {
            $j('#fsToppingTotal').addClass('fss-hide').text('');
        }

        $j('#fsToppingTotal')
            .text(
                `(${price.toLocaleString('ro-RO', {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2,
                })} lei cu topping-uri)`
            )
            .removeClass('fss-hide');
    }

    private toggleToppingFromCheckbox(freyaCode: string, priceUpdate: boolean) {
        if ($j(`#checkbox-${freyaCode}`).is(':checked')) {
            $j(`#${freyaCode}`).removeClass('fss-hide');
            this.setToppingAsActive(freyaCode);
        } else {
            $j(`#${freyaCode}`).addClass('fss-hide');
            this.disableTopping(freyaCode);
        }

        if (priceUpdate) {
            this.updateToppingPrice();
        }
    }
}
