<template>
    <!--========ITEM PART START=========-->
    <div v-if="design === itemDesignEnum.LIST" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 md:gap-6">
        <div v-for="item in items" :key="item" v-show="type === null || type === item.item_type"
            class="product-card-list">
            <img @click.prevent="variationModalShow(item)" class="product-card-list-image cursor-pointer"
                :src="item.thumb" alt="thumbnail">
            <div class="product-card-list-content-group">
                <div class="product-card-list-header-group">
                    <h3 class="product-card-list-title">{{ textShortener(item.name, 25) }}</h3>
                    <button v-if="item.caution" class="product-card-list-info-btn info-btn flex items-start"
                        data-modal="#item-info-modal" @click.prevent="infoModalShow(item.name, item.caution)">
                        <i class="lab lab-information font-fill-paragraph transition lab-font-size-16"></i>
                    </button>
                </div>
                <p class="product-card-list-describe char-limit">
                    {{ textShortener(item.description, 65) }}
                </p>
                <div class="product-card-list-footer-group">
                    <div class="product-card-list-price-group">
                        <h4 class="product-card-list-price-current">
                            {{ item.currency_price }}
                        </h4>
                    </div>
                    <button @click.prevent="variationModalShow(item)" data-modal="#item-variation-modal"
                        class="product-card-list-cart-btn add-btn group">
                        <i class="lab lab-bag-2 lab-font-size-14 text-primary transition group-hover:text-white"></i>
                        <span class="text-xs text-primary transition group-hover:text-white">{{ $t('button.add')
                        }}</span>
                    </button>
                </div>
            </div>
        </div>
    </div>
    <div v-else-if="design === itemDesignEnum.GRID"
        class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3 lg:gap-6">
        <div v-for="item in items" :key="item" v-show="type === null || type === item.item_type"
            class="product-card-grid">
            <img @click.prevent="variationModalShow(item)" class="product-card-grid-image cursor-pointer"
                :src="item.cover" alt="product">
            <div class="product-card-grid-content-group">
                <div class="product-card-grid-header-group">
                    <h3 class="product-card-grid-title">{{ textShortener(item.name, 26) }}</h3>
                    <button v-if="item.caution" type="button" class="product-card-grid-info-btn info-btn"
                        data-modal="#item-info-modal" @click.prevent="infoModalShow(item.name, item.caution)">
                        <i class="lab lab-information font-fill-paragraph transition lab-font-size-16"></i>
                    </button>
                </div>
                <p class="product-card-grid-describe char-limit">{{ textShortener(item.description, 75) }}</p>
                <div class="product-card-grid-footer-group">
                    <div class="product-card-grid-price-group">
                        <h4 class="product-card-grid-price-current">
                            {{ item.currency_price }}
                        </h4>
                    </div>
                    <button @click.prevent="variationModalShow(item)" data-modal="#item-variation-modal"
                        class="product-card-list-cart-btn add-btn group">
                        <i class="lab lab-bag-2 lab-font-size-14 text-primary transition group-hover:text-white"></i>
                        <span class="text-xs text-primary transition group-hover:text-white">{{ $t('button.add')
                        }}</span>
                    </button>
                </div>
            </div>
        </div>
    </div>
    <!--========ITEM PART END===========-->

    <!--========INFO PART START=========-->
    <div id="item-info-modal" ref="itemInfoModal" class="modal info-modal">
        <div class="modal-dialog">
            <div class="modal-header">
                <h3 class="modal-title text-base font-medium">{{ itemInfo?.name }}</h3>
                <button class="close-modal lab-close-circle-line text-negative text-base"
                    @click.prevent="infoModalHide"></button>
            </div>
            <div class="modal-body">
                {{ itemInfo?.caution }}
            </div>
        </div>
    </div>
    <!--========INFO PART END===========-->

    <!--========VARIATION PART START=========-->

    <section id="item-variation-modal" class="frontend-modal" ref="itemVariationModal">
        <div class="max-w-[456px] w-full bg-white p-4 scale-0 transition-all duration-500 rounded-2xl absolute top-20">
            <div class="items-start border-none mb-4 flex justify-between gap-6">
                <div class="flex gap-4">
                    <img class="flex-shrink-0 w-[72px] h-[72px] object-cover rounded-lg" :src="item?.thumb"
                        alt="thumbnail">
                    <div class="flex-auto">
                        <div class="flex items-start gap-2 mb-1">
                            <h3 class="text-sm font-semibold capitalize">{{ item?.name }}</h3>
                            <button v-if="item?.caution" type="button"
                                @click.prevent="infoModalShow(item?.name, item?.caution)" class="info-btn"
                                data-modal="#item-info-modal">
                                <i class="lab lab-information text-black/80"></i>
                            </button>
                        </div>
                        <p class="text-xs text-justify mb-2">{{ item?.description }}</p>
                        <h4 class="text-sm font-semibold">{{ item?.currency_price }}</h4>
                    </div>
                </div>
                <button @click.prevent="variationModalHide"
                    class="close-modal lab-close-circle-line text-negative text-base"></button>
            </div>
            <div>
                <div class="flex items-center sm:justify-start justify-between gap-2 mb-4">
                    <h3 class="text-sm leading-6 font-medium first-letter:uppercase text-heading"> {{
                        $t('label.quantity') }}:</h3>
                    <div class="flex items-center indec-group py-1 px-2 rounded-xl bg-[#F7F7FC]">
                        <button @click.prevent="quantityDecrement"
                            class="fa-solid fa-minus text-[8px] w-4 h-4 leading-4 text-center rounded-full border transition text-primary border-primary hover:bg-primary hover:text-white indec-minus"></button>
                        <input type="number" v-model="temp.quantity" v-on:keypress="onlyNumber($event)"
                            v-on:keyup="quantityUp"
                            class="text-center w-7 text-xs font-semibold text-heading indec-value bg-transparent">
                        <button @click.prevent="quantityIncrement"
                            class="fa-solid fa-plus text-[8px] w-4 h-4 leading-4 text-center rounded-full border transition text-primary border-primary hover:bg-primary hover:text-white indec-plus"></button>
                    </div>
                </div>

                <div class="mb-4" v-if="item?.itemAttributes.length > 1">
                    <div class="row">
                        <div v-for="itemAttribute in item?.itemAttributes" class="col-12 sm:col-6">
                            <label class="text-sm leading-6 block font-medium capitalize mb-1.5 text-heading">
                                {{ itemAttribute.name }}
                            </label>
                            <div class="relative">
                                <i
                                    class="lab lab-arrow-down text-sm absolute top-1/2 ltr:right-2.5 rtl:left-2.5 -translate-y-1/2 lab-font-size-16"></i>
                                <select
                                    @change.prevent="changeVariationAdjust(itemAttribute.id, temp.item_variations.variations[itemAttribute.id])"
                                    v-model="temp.item_variations.variations[itemAttribute.id]"
                                    class="text-xs capitalize rounded-lg h-10 w-full py-1.5 px-2.5 appearance-none transition border border-[#EFF0F6] text-heading hover:border-primary/30">
                                    <option :value="variation.id" v-for="variation in item.variations[itemAttribute.id]"
                                        :key="variation">{{ variation.name }} +{{ variation.currency_price }}
                                    </option>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="mb-4" v-else-if="item?.itemAttributes.length > 0">
                    <h3 class="text-sm leading-6 font-medium capitalize mb-2 text-heading ltr:text-left rtl:text-right">
                        {{ item?.itemAttributes[0].name }}
                    </h3>
                    <div dir="ltr" class="swiper size-swiper">
                        <div class="size-tabs">
                            <Swiper :speed="1000" slidesPerView="auto" :spaceBetween="16">
                                <SwiperSlide v-for="variation in item?.variations[item.itemAttributes[0].id]"
                                    :key="variation" class="!w-fit !relative">
                                    <label
                                        :class="temp.item_variations.variations[variation.item_attribute_id] === variation.id ? 'active' : ''"
                                        :for="variation.item_attribute_id + '-' + variation.name"
                                        class="w-full min-w-[120px] h-[52px] cursor-pointer py-2 px-3 gap-2 rounded-lg flex items-center border transition border-[#F7F7FC] bg-[#F7F7FC]">
                                        <div class="custom-radio sm">
                                            <input :value="variation.id"
                                                @click="changeVariation(variation.item_attribute_id, variation.id, variation.name, variation.convert_price)"
                                                v-model="temp.item_variations.variations[variation.item_attribute_id]"
                                                type="radio" :id="variation.item_attribute_id + '-' + variation.name"
                                                class="custom-radio-field">
                                            <span class="custom-radio-span"></span>
                                        </div>
                                        <div class="ltr:text-left rtl:text-right">
                                            <h3 class="block capitalize text-xs text-heading">
                                                {{ textShortener(variation.name, 15) }}</h3>
                                            <h4 v-if="variation.price > 0"
                                                class="block text-xs font-medium text-heading">
                                                +{{ variation.currency_price }}
                                            </h4>
                                        </div>
                                    </label>
                                </SwiperSlide>
                            </Swiper>
                        </div>
                    </div>
                </div>
                <div class="mb-6">
                    <h3 class="text-xs leading-6 font-medium capitalize mb-2 text-heading">
                        {{ $t('label.special_instructions') }}
                    </h3>
                    <textarea v-model="temp.instruction" :placeholder="$t('message.add_note')"
                        class="h-12 w-full rounded-lg border py-1.5 px-2 placeholder:text-[10px] placeholder:text-[#6E7191] border-[#D9DBE9]"></textarea>
                </div>
                <button type="button" :disabled="temp.total_price <= 0" @click.prevent="addToCart"
                    class="flex items-center justify-center gap-3 rounded-3xl text-base py-3 px-3 font-medium w-full text-white bg-primary cursor-pointer">
                    <i class="icon-cart"></i>
                    <span>{{ $t('button.add_to_cart') }} -
                        {{
                            currencyFormat(temp.total_price, setting.site_digit_after_decimal_point,
                                setting.site_default_currency_symbol, setting.site_currency_position)
                        }}</span>
                </button>
            </div>

        </div>
    </section>
    <!--========VARIATION PART END===========-->
</template>
<script>
import itemDesignEnum from "../../../enums/modules/itemDesignEnum";
import mealTypeEnum from "../../../enums/modules/mealTypeEnum";
import appService from "../../../services/appService";
import _ from 'lodash';
import alertService from "../../../services/alertService";
import { Swiper, SwiperSlide } from 'swiper/vue';
import 'swiper/css';
import VueDatePicker from '@vuepic/vue-datepicker';
import '@vuepic/vue-datepicker/dist/main.css'
import statusEnum from "../../../enums/modules/statusEnum";
import { useFrontendSettingStore } from "../../../stores/frontend/frontendSetting";
import { useFrontendItemStore } from "../../../stores/frontend/frontendItem";
import { useFrontendCartStore } from "../../../stores/frontend/frontendCart";


export default {
    name: "ItemComponent",
    components: {
        Swiper,
        SwiperSlide,
        VueDatePicker
    },
    props: {
        items: Object,
        design: Number,
        type: Number
    },
    data() {
        return {
            item: null,
            itemInfo: null,
            itemArrays: [],
            itemDesignEnum: itemDesignEnum,
            settings: {
                itemsToShow: 4.3,
                wrapAround: false,
                snapAlign: "start"
            },
            temp: {
                name: "",
                image: "",
                item_id: 0,
                quantity: 0,
                discount: 0,
                currency_price: 0,
                convert_price: 0,
                item_variations: {
                    variations: {},
                    names: {}
                },
                item_category: {},
                item_variation_total: 0,
                total_price: 0,
                instruction: "",
                taxes: {},
            },
            deliveryDaysList: [],
            frontendSettingStore: useFrontendSettingStore(),
            frontendItemStore: useFrontendItemStore(),
            frontendCartStore: useFrontendCartStore(),
        }
    },
    computed: {
        setting: function () {
            return this.frontendSettingStore.lists;
        },
        cartMealType: function () {
            return this.frontendCartStore.mealTypes;
        },
    },
    methods: {
        onlyNumber: function (e) {
            return appService.onlyNumber(e);
        },
        calculateMaxDate() {
            const duration = this.setting.site_order_accept_duration;
            const today = new Date();
            const maxDate = new Date(today);
            maxDate.setDate(today.getDate() + +duration);
            return maxDate;
        },
        textShortener: function (text, number) {
            return appService.textShortener(text, number);
        },
        currencyFormat: function (amount, decimal, currency, position) {
            return appService.currencyFormat(amount, decimal, currency, position);
        },
        infoModalShow: function (name, caution) {
            this.itemInfo = {
                name: name,
                caution: caution
            };
            const modalTarget = this.$refs.itemInfoModal;
            modalTarget?.classList?.add("active");
            document.body.style.overflowY = "hidden";
        },
        infoModalHide: function () {
            this.itemInfo = null;
            const modalDiv = this.$refs.itemInfoModal;
            modalDiv?.classList?.remove("active");
            document.body.style.overflowY = "auto";
        },
        variationModalShow: function (selectedItem) {

            this.frontendItemStore.details(selectedItem.id)
                .then((res) => {
                    const item = res.data.data;
                    this.item = res.data.data;

                    if (this.item.itemAttributes.length > 0) {
                        _.forEach(this.item.itemAttributes, (element) => {
                            if (typeof this.item.variations[element.id][0] !== "undefined") {
                                this.temp.item_variations.variations[this.item.variations[element.id][0].item_attribute_id] = this.item.variations[element.id][0].id;
                                this.temp.item_variations.names[element.name] = this.item.variations[element.id][0].name;
                                this.temp.item_variation_total += this.item.variations[element.id][0].convert_price;
                            }
                        });
                    }

                    this.temp.item_category = { id: this.item.category.id, name: this.item.category.name };
                    this.temp.name = this.item.name;
                    this.temp.image = this.item.thumb;
                    this.temp.item_id = this.item.id;
                    this.temp.quantity = 1;
                    this.temp.discount = 0;
                    this.temp.convert_price = item.convert_price;
                    this.temp.currency_price = item.currency_price;
                    this.temp.total_price = item.convert_price + this.temp.item_variation_total;
                    this.temp.taxes = this.item.taxes;

                    const modalTarget = this.$refs.itemVariationModal;
                    modalTarget?.classList?.add("active");
                    document.body.style.overflowY = "hidden";
                }).catch({});
        },
        variationModalHide: function () {
            this.item = null;
            this.temp.item_category = {};
            this.temp.name = "";
            this.temp.image = "";
            this.temp.item_id = 0;
            this.temp.quantity = 0;
            this.temp.discount = 0;
            this.temp.currency_price = 0;
            this.temp.convert_price = 0;
            this.temp.total_price = 0;
            this.temp.item_variations = {
                variations: {},
                names: {}
            };
            this.temp.item_variation_total = 0;
            this.temp.taxes = {};

            const modalDiv = this.$refs.itemVariationModal;
            modalDiv?.classList?.remove("active");
            document.body.style.overflowY = "auto";
        },
        changeVariation: function (attributeId, variationId, variationName, variationPrice) {
            this.temp.item_variations.variations[attributeId] = variationId;
            _.forEach(this.item.itemAttributes, (element) => {
                if (element.id === attributeId) {
                    this.temp.item_variations.names[element.name] = variationName;
                }
            });
            this.totalPriceSetup();
        },
        changeVariationAdjust: function (attributeId, variationId) {
            _.forEach(this.item.variations[attributeId], (variation) => {
                if (variation.id === variationId) {
                    this.changeVariation(attributeId, variationId, variation.name, variation.convert_price);
                }
            });
        },
        totalPriceSetup: function () {
            let item_variation_total = 0;
            _.forEach(this.temp.item_variations.variations, (variationId, attributeId) => {
                _.forEach(this.item.variations[attributeId], (itemVariation) => {
                    if (variationId === itemVariation.id) {
                        item_variation_total += itemVariation.convert_price;
                    }
                });
            });

            this.temp.item_variation_total = item_variation_total;
            this.temp.total_price = parseFloat(((this.item.convert_price + this.temp.item_variation_total) * this.temp.quantity));

        },
        quantityUp: function () {
            if (this.temp.quantity === 0) {
                this.temp.quantity = 1;
            }
            this.totalPriceSetup();
        },
        quantityIncrement: function () {
            this.temp.quantity++;
            if (this.temp.quantity <= 0) {
                this.temp.quantity = 1;
            }
            this.totalPriceSetup();
        },
        quantityDecrement: function () {
            this.temp.quantity--;
            if (this.temp.quantity <= 0) {
                this.temp.quantity = 1;
            }
            this.totalPriceSetup();
        },
        addToCart: function () {
            this.itemArrays = [
                {
                    item_category: this.temp.item_category,
                    name: this.temp.name,
                    image: this.temp.image,
                    item_id: this.temp.item_id,
                    quantity: this.temp.quantity,
                    discount: this.temp.discount,
                    currency_price: this.temp.currency_price,
                    convert_price: this.temp.convert_price,
                    item_variations: this.temp.item_variations,
                    item_variation_total: this.temp.item_variation_total,
                    instruction: this.temp.instruction,
                    taxes: this.temp.taxes
                }
            ];

            if (this.itemArrays.length > 0) {
                this.frontendCartStore.fetchLists(this.itemArrays).then((res) => {
                    this.item = null;
                    this.temp.item_category = {};
                    this.temp.name = "";
                    this.temp.image = "";
                    this.temp.item_id = 0;
                    this.temp.quantity = 0;
                    this.temp.discount = 0;
                    this.temp.currency_price = 0;
                    this.temp.convert_price = 0;
                    this.temp.item_variations = {
                        variations: {},
                        names: {}
                    };
                    this.temp.taxes = {};
                    this.temp.item_variation_total = 0;
                    this.temp.total_price = 0;
                    this.temp.instruction = "";
                    this.itemArrays = [];

                    alertService.success(this.$t('message.add_to_cart'));
                    const modalDiv = this.$refs.itemVariationModal;
                    modalDiv?.classList?.remove("active");
                    document.body.style.overflowY = "auto";
                }).catch();
            }
        },
    }
}
</script>

<style>
.dp__flex_display {
    display: block !important;
}

.dp__theme_light {
    --dp-primary-color: rgba(207 1 6) !important;
}
</style>