<template>
    <BsDrawer>

        <BsExpandableSection header-text="Product" selector-label="" :disabled="!products.length">
            <BsWarning text='Select the product you want to see' style="max-width: 100%;" class="spacing"></BsWarning>
            <BsSelect v-model="selectedProduct" :options="productOptions" clear-icon="clear" @filter="filterFn" use-input
                clearable input-debounce="0" :disable="!products.length">
                <template v-slot:selected-item="scope">
                    <div v-if="scope.opt">
                        <CustomizedProduct :product="scope.opt" style="padding-top: 5px"></CustomizedProduct>
                    </div>
                </template>
                <template v-slot:option="scope">
                    <div v-if="scope.opt" v-bind="scope.itemProps" class="product-el">
                        <CustomizedProduct :product="scope.opt" style="padding: 10px"></CustomizedProduct>
                    </div>
                </template>
            </BsSelect>
        </BsExpandableSection>
    </BsDrawer>
    <div v-if="!products.length" class="flex-column-20">
        <div class="bs-font-medium-4-semi-bold">No product values</div>
        <BsWarning>
            <div>
                If you want to see product values:
                <ul style="margin-top: 0px; padding-inline-start: 20px">
                    <li>
                        go to "Product selection" and select products to
                        customize
                    </li>
                    <li>
                        rerun for reviewing the impact of the customization'
                    </li>
                </ul>
            </div>
        </BsWarning>
    </div>
    <EmptyState title="Customization results" subtitle="Select a product in the left panel to see product values"
        v-else-if="products && !selectedProduct"></EmptyState>

    <Summary :title="selectedProduct.id" :big-cards="bigCards" :small-cards="smallCards"
        warning-msg="No results are available now. You need to have first customised markdown for products. For this, please configure the previous tab, “Markdown customization”."
        :show-warning="!customizedRow.result" v-else>
        <div class="bs-font-large-1-semi-bold title">Product Performances</div>
        <div style="display: inline-flex; gap: 20px">
            <div>
                <img src="../../assets/images/bar-legend-initial.svg" /> Initial
                optimization
            </div>
            <div>
                <img src="../../assets/images/bar-legend-customization.svg" />
                Customization
            </div>
        </div>
        <div class="charts-container">
            <VerticalBarChart class="bar-chart" title="Monetary Value ($)" :data="chartDataProfitRevenue"
                v-if="chartDataProfitRevenue" />
            <!-- Sales Volume & Lost Sales Volume Chart -->
            <VerticalBarChart class="bar-chart" title="Number of units" :data="chartDataSalesVolumeLostSales"
                v-if="chartDataSalesVolumeLostSales" />
            <!-- Margin & Sellthrough Chart -->
            <VerticalBarChart class="bar-chart" title="%" :data="chartDataMarginSellthrough"
                v-if="chartDataMarginSellthrough" />
        </div>
    </Summary>
</template>

<script lang="ts">
import { defineComponent } from "vue";

import useProductStore from "../../store/ProductStore.js";
import BsWarning from "../BsWarning.vue";
import Summary from "../Summary.vue";
import BsExpandableSection from "../BsExpandableSection.vue";
import VerticalBarChart from "../VerticalBarChart.vue";
import EmptyState from "../EmptyState.vue";
import CustomizedProduct from "../CustomizedProduct.vue";
import { CARD_LABELS, CHART_LABELS, SMALL_CARDS_KEYS, appendCurrency, formatDate, formatNumbers } from "../utils";
export default defineComponent({
    components: {
        BsWarning,
        Summary,
        BsExpandableSection,
        VerticalBarChart,
        EmptyState,
        CustomizedProduct,
    },
    data() {
        return {
            bigCards: [],
            smallCards: [],
            products: [] as any[],
            selectedProduct: undefined as undefined | any,
            store: undefined as undefined | any,
            chartDataProfitRevenue: [] as any[],
            chartDataSalesVolumeLostSales: [] as any[],
            chartDataMarginSellthrough: [] as any[],
            customizedRow: {} as any,
            productOptions: [] as any[],
            // Configurations for the cards
            cardConfig: {
                bigCards: [
                    {
                        title: appendCurrency("total_profit", useProductStore().currency),
                        key: "total_profit",
                        infoText:
                            "Compare the 'Profit' KPI results between the initial optimization and the results of your markdown customization",
                    },
                    {
                        title: appendCurrency("forecasted_volume", useProductStore().currency),
                        key: "forecasted_volume",
                        infoText:
                            "Compare the 'Volume' KPI results between the initial optimization and the results of your markdown customization",
                    },
                ],
            },
        };
    },
    mounted() {
        this.store = useProductStore();
    },
    methods: {
        filterFn(val: string, update: any) {
            update(() => {
                const needle = val?.toLowerCase() || "";
                this.productOptions = val
                    ? this.products.filter(
                        (v) =>
                            JSON.stringify(v)
                                .toLowerCase()
                                .indexOf(needle.toLowerCase()) > -1
                    )
                    : this.products;
            });
        },
        generateCardData(cardConfig: any) {
            return cardConfig.map((config: any) => ({
                title: config.title,
                items: {
                    "Initial optimization":
                        formatNumbers(this.customizedRow.initial[config.key] || 0),
                    Customization: this.customizedRow.result
                        ? formatNumbers(this.customizedRow.result[config.key] || 0) : 0

                },
                infoText: config.infoText,
            }));
        },
        buildCards() {
            this.bigCards = this.generateCardData(this.cardConfig.bigCards);
            this.smallCards = this.generateCardData(
                SMALL_CARDS_KEYS.map((el: string) => {
                    if (el === 'margin_percent') {
                        el = "margin";
                    }
                    return {
                        title: appendCurrency(el, this.store.currency),
                        key: el,
                    };
                })
            );
        },
        getChartData(key: string, label?: string) {
            const title = label || CHART_LABELS[key] || key

            return [
                {
                    label: title,
                    value: this.customizedRow.initial[key],
                    type: "initial",
                },
                {
                    label: title,
                    value: this.customizedRow.result
                        ? this.customizedRow.result[key]
                        : 0,
                    type: "customization",
                },
            ];
        },
        updateUI() {
            this.buildCards();
            this.chartDataProfitRevenue = this.getChartData(
                "total_profit"
            ).concat(this.getChartData("revenue", "Sales \n Revenues"));
            this.chartDataSalesVolumeLostSales = this.getChartData(
                "forecasted_volume", "Sales \n Volume"
            ).concat(this.getChartData("lost_sales", " Lost Sales \n Volume"));
            // console.log("data:",this.chartDataSalesVolumeLostSales)
            this.chartDataMarginSellthrough = this.getChartData(
                "margin", "Margin"
            ).concat(this.getChartData("sellthrought_rate"));
        },
        getProducts() {
            this.products = Array.from(this.store.resultProdcutNames).map(
                (productId) => {
                    const product =
                        this.store.getCustomizedRow(productId).initial;
                    // console.log(
                    //     "product:",
                    //     product.product_id,
                    //     product.timestamp,
                    //     product.username
                    // );
                    const formattedDate = product.timestamp
                        ? formatDate(product.timestamp).fullWithUSTimestamp
                        : null;
                    return {
                        id: productId,
                        customizationDate: formattedDate,
                        userEmail: product.username,
                    };
                }
            );
        },
    },
    watch: {
        selectedProduct() {
            if (this.selectedProduct) {
                this.customizedRow = this.store.getCustomizedRow(
                    this.selectedProduct.id
                );

                this.updateUI();
            }
        },
        "store.customizationResults.keys()"(newVal, oldVal) {
            // console.log("keys changes", newVal, oldVal);
            this.getProducts();
        },
        "store.resultProdcutNames"() {
            this.getProducts();
        },
    },
});
</script>
<style scoped>
.button {
    border-radius: 8px;
    background-color: #4caf50;
    color: white;
}

.button:hover {
    box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
        0 17px 50px 0 rgba(0, 0, 0, 0.19);
}

.spacing {
    margin-bottom: 2rem;
}

.container {
    display: flex;
}

.flex_display {
    display: flex;
    flex-direction: row;
    padding-top: 2%;
}

.flex_column {
    display: flex;
    flex-direction: column;
    width: 50%;
}

.container_grid {
    display: grid;
    grid-template-columns: 0.4fr 0.3fr 0.3fr;
    grid-column-gap: 10px;
    grid-row-gap: 15px;
}

.card {
    width: 300px;
}

.box {
    width: 320px;
    padding: 10px;
    border-left: 5px solid gray;
    margin: 0;
}

:deep(.q-field__native) {
    height: 100% !important;
}

.product-el:focus,
.product-el:hover {
    background-color: var(--interactions-bs-color-interaction-primary, #2b66ff);
    color: white;
}
</style>
