<template>
    <div class="cart">
        <div class="container-fluid px-0">
            <div
                class="row vin-toggle flex align-items-center"
                :class="[isActive ? 'active' : '']"
                @click="toggleClass()">
                <div class="col d-flex justify-content-between">
                    <span class="label">Amount Due</span
                    ><span class="label amount-due">{{ currencyFormatter.format(amountDue) }}</span>
                </div>
            </div>
            <div class="price-table">
                <div class="service-type" :class="{ packageWithVAPS: packageWithVAPS }">
                    <textBlock :cmsWidgetName="servicePackageTitleWidget" /><span>{{
                        currencyFormatter.format(packagePrice)
                    }}</span>
                </div>
                <div
                    v-for="(cartItem, i) in packageCartItems"
                    :key="i"
                    :class="[this.packageCartItems ? 'vaps' : '']">
                    <span>{{ cartItem.name }}</span>
                    <textLink
                        ref="removeLink"
                        linkType="text"
                        :text="removeLinkText"
                        href="#!"
                        @click-event="removeItem(cartItem)" />
                </div>
                <hr style="background: red" />
                <div v-for="(cartItem, i) in nonpackageCartItems" :key="i">
                    <span>{{ cartItem.name }}</span>
                    <textLink
                        ref="removeLink"
                        linkType="text"
                        :text="removeLinkText"
                        href="#!"
                        @click-event="removeItem(cartItem)" />
                    <span>{{ currencyFormatter.format(cartItem.subTotal) }}</span>
                </div>
                <div v-if="hasRecycleLineItem">
                    <span>{{ recycleLabel }}</span
                    ><span>{{ recycleFee }}</span>
                </div>
                <!-- Sub total, sales tax, total columns -->
                <div class="sub-total">
                    <span>Subtotal</span><span>{{ currencyFormatter.format(subTotal) }}</span>
                </div>
                <div class="sales-tax">
                    <span>Sales tax</span><span>{{ currencyFormatter.format(salesTax) }}</span>
                </div>
                <div class="amount-due">
                    <span>Amount due</span><span>{{ currencyFormatter.format(amountDue) }}</span>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import baseMixin from "@/mixins/base-mixin.js";
import {
    getHighestFullySatisfiedTier,
    containsLineItemWithPartType,
    getPackageContents,
    findLineItemsWithPartType,
} from "@/helpers/service-package-helper";
import textLink from "@/ux-components/text-link/text-link";
import textBlock from "@/digital-components/text-block/text-block";
import { LineItemUtilities } from "@/store";


export default {
    name: "modal",
    props: {
        modelValue: Object,
        damage: Object,
        servicePackageOptionsCmsName: String,
        availableLineItems: Object,
    },
    data() {
        return {
            isActive: false,
            packageWithVAPS: false,
            currencyFormatter: new Intl.NumberFormat("en-US", {
                style: "currency",
                currency: "USD",
            }),
            lineItemUtilities: new LineItemUtilities(),    
        };
    },
    methods: {
        toggleClass: function (event) {
            this.isActive = !this.isActive;
        },
        getVapsPrice(packageName) {
            const vapsItems = this.getVapsCartItemsForSelectedPackage(packageName);

            let subTotal = 0;

            vapsItems.forEach((item) => {
                subTotal += item.subTotal; //    baseMixin.methods.getTotalLineItemPrice(item);
            });

            return subTotal;
        },
        removeItem(cartItem) {
            this.lineItems[cartItem.category] = this.lineItems[cartItem.category].filter(lineItem => lineItem.partType != cartItem.cartItemType);
        },
        getVapsCartItemsForSelectedPackage(packageName) {
            const packageContentTypes = getPackageContents(
                this.glassToReplace,
                this.availableLineItems,
                this.isRepair,
                packageName
            );

            let vapsCartItemsForSelectedPackage = [];

            this.cartItems.forEach((cartItem) => {
                packageContentTypes.forEach((vapType) => {
                    if (vapType == cartItem.cartItemType) {
                        vapsCartItemsForSelectedPackage.push(cartItem);
                    }
                })
            })

            return vapsCartItemsForSelectedPackage;
        },
        getCmsContentForVapsType(vapsType) {
            const vapsItemDescriptions = this.getCmsContent(
                "VapsItemDescriptions",
                "Answers"
            );

            if (!vapsItemDescriptions) {
                return "";
            }

            const vapsTypeName = vapsItemDescriptions.find(
                (entry) => entry.Name === vapsType
            );

            return vapsTypeName.Text;
        }
    },
    computed: {
        lineItems: {
            get: function () {
                return this.modelValue;
            },
            set: function (newValue) {
                this.$emit("update:modelValue", newValue);
            },
        },
        cartItems: {
            get: function () {
                let cartItems = [];

                if (this.frontWipersCartItem) {
                    cartItems.push(this.frontWipersCartItem);
                }

                if (this.rearWipersCartItem) {
                    cartItems.push(this.rearWipersCartItem);
                }

                if (this.rainDefenseCartItem) {
                    cartItems.push(this.rainDefenseCartItem);
                }

                if (this.glassPartsCartItem) {
                    cartItems.push(this.glassPartsCartItem);
                }

                if (this.supportingItemsCartItem) {
                    cartItems.push(this.supportingItemsCartItem);
                }

                return cartItems;
            },
            set: function (newValue) {},
        },
        servicePackageTitleWidget() {
            const servicePackageNames = this.getCmsContent(
                this.servicePackageOptionsCmsName,
                "Answers"
            );

            if (!servicePackageNames) {
                return "";
            }

            const currentPackage = servicePackageNames.find(
                (entry) => entry.Name === this.packageLevel
            );

            return currentPackage.SubWidgetName;
        },
        packageLevel() {
            const tier = getHighestFullySatisfiedTier(
                this.glassToReplace,
                this.availableLineItems,
                this.isRepair,
                this.vaps
            );

            return tier;
        },
        packagePrice() {
            let packagePrice = this.isInsuranceSelected
                ? 0
                : baseMixin.methods.getTierOnePackagePrice(
                      baseMixin.methods.filterOutFees(this.availableLineItems)
                  );

            packagePrice += this.getVapsPrice(this.packageLevel);

            return packagePrice;
        },
        vaps() {
            const vaps = this.lineItems?.vaps;
            return vaps?.length > 0 ? vaps : [];
        },
        frontWipersCartItem() {
            let cartItem = null;

            const frontWiperLineItems = this.vaps.filter(
                (vapsLineItem) => vapsLineItem.partType == "FRONT WIPER"
            );

            if (frontWiperLineItems.length > 0) {
                cartItem = {
                    name: this.getCmsContentForVapsType("FRONT WIPER"), //"Front Wipers", // TODO: Get from CMS
                    category: "vaps",
                    cartItemType: "FRONT WIPER",
                    subTotal: 0,
                    salesTax: 0,
                    lineItems: [],
                };

                frontWiperLineItems.forEach((lineItem) => {
                    cartItem.lineItems.push(lineItem);

                    cartItem.subTotal += 
                        (lineItem.kitPrice ?? 0) +
                        (lineItem.laborAmount ?? 0) +
                        (lineItem.sellingPrice ?? 0);

                    cartItem.salesTax += lineItem.salesTax ?? 0; 
                });
            }

            return cartItem;
        },
        rearWipersCartItem() {
            let cartItem = null;

            const rearWiperLineItems = this.vaps.filter(
                (vapsLineItem) => vapsLineItem.partType == "REAR WIPER"
            );

            if (rearWiperLineItems.length > 0) {
                cartItem = {
                    name: this.getCmsContentForVapsType("REAR WIPER"), // TODO: Get from CMS
                    category: "vaps",
                    cartItemType: "REAR WIPER",
                    subTotal: 0,
                    salesTax: 0,
                    lineItems: [],
                };

                rearWiperLineItems.forEach((lineItem) => {
                    cartItem.lineItems.push(lineItem);

                    cartItem.subTotal += 
                        (lineItem.kitPrice ?? 0) +
                        (lineItem.laborAmount ?? 0) +
                        (lineItem.sellingPrice ?? 0);

                    cartItem.salesTax += lineItem.salesTax ?? 0; 
                });
            }

            return cartItem;
        },
        rainDefenseCartItem() {
            let cartItem = null;

            const rainDefenseLineItems = this.vaps.filter(
                (vapsLineItem) => vapsLineItem.partType == "RAIN DEFENSE"
            );

            if (rainDefenseLineItems.length > 0) {
                cartItem = {
                    name: this.getCmsContentForVapsType("RAIN DEFENSE"), // TODO: Get from CMS
                    category: "vaps",
                    cartItemType: "RAIN DEFENSE",
                    subTotal: 0,
                    salesTax: 0,
                    lineItems: [],
                };

                rainDefenseLineItems.forEach((lineItem) => {
                    cartItem.lineItems.push(lineItem);

                    cartItem.subTotal += 
                        (lineItem.kitPrice ?? 0) +
                        (lineItem.laborAmount ?? 0) +
                        (lineItem.sellingPrice ?? 0);

                    cartItem.salesTax += lineItem.salesTax ?? 0; 
                });
            }

            return cartItem;
        },
        glassPartsCartItem() {
            let cartItem = null;

            const flattenedGlassPartsLineItems = this.lineItemUtilities.getFlattenedArrayOfLineItemsWithChildParts(
                this.lineItems.glassParts);

            if (flattenedGlassPartsLineItems.length > 0) {
                cartItem = {
                    name: "Glass Parts", // TODO: Get from CMS
                    category: "glassParts",
                    cartItemType: "GLASS PARTS",
                    subTotal: 0,
                    salesTax: 0,
                    lineItems: [],
                };

                flattenedGlassPartsLineItems.forEach((lineItem) => {
                    cartItem.lineItems.push(lineItem);

                    cartItem.subTotal += 
                        (lineItem.kitPrice ?? 0) +
                        (lineItem.laborAmount ?? 0) +
                        (lineItem.sellingPrice ?? 0);

                    cartItem.salesTax += lineItem.salesTax ?? 0; 
                });
            }

            return cartItem;
        },
        supportingItemsCartItem() {
            let cartItem = null;

            if (this.supportingItems.length > 0) {
                cartItem = {
                    name: "Supporting Items", // TODO: Get from CMS
                    category: "supportingItems",
                    cartItemType: "SUPPORTING ITEMS",
                    subTotal: 0,
                    salesTax: 0,
                    lineItems: [],
                };

                this.supportingItems.forEach((lineItem) => {
                    cartItem.lineItems.push(lineItem);

                    cartItem.subTotal += 
                        (lineItem.kitPrice ?? 0) +
                        (lineItem.laborAmount ?? 0) +
                        (lineItem.sellingPrice ?? 0);

                    cartItem.salesTax += lineItem.salesTax ?? 0; 
                });
            }

            return cartItem;
        },
        packageCartItems() {
            if (this.packageLevel == "TierThree") {
                return this.cartItems.filter(cartItem => cartItem.category == "vaps");
            } else if (this.packageLevel == "TierTwo") {
                return this.cartItems.filter(cartItem => cartItem.cartItemType == "FRONT WIPER" || cartItem.cartItemType == "REAR WIPER");
            }

            return [];
        },
        nonpackageCartItems() {
            if (this.packageLevel == "TierOne" && this.rainDefenseCartItem) {
                return this.cartItems.filter(cartItem => cartItem.cartItemType == "RAIN DEFENSE");
            }

            return [];
        },
        glassToReplace() {
            if (!this.damage) {
                return;
            }

            return this.damage.glassToReplace;
        },
        isRepair() {
            if (!this.damage) {
                return;
            }

            return this.damage.isRepair;
        },
        supportingItems() {
            const supportingItems = this.lineItems?.supportingItems;
            return supportingItems?.length > 0 ? supportingItems : [];
        },
        removeLinkText() {
            return "Remove"; // TODO: get from CMS
        },
        recycleLabel() {
            return "Recycling";
        },
        recycleFee() {
            return "$35.00";
        },
        hasRecycleLineItem() {
            //TO DO
            // if (this.lineItems.supportingItems[0].partNumber === "RECYCLE FEE") {
            //     return true;
            // } else {
            //     return false;
            // }
            return true;
        },
        subTotal() {
            let subTotal = 0;

            this.cartItems.forEach((cartItem) => {
                subTotal += cartItem.subTotal;
            });

            return subTotal;
        },
        salesTax() {
            let salesTax = 0;
            this.cartItems.forEach((cartItem) => {
                console.log(cartItem.salesTax)
                salesTax += cartItem.salesTax ?? 0;
            });

            return salesTax;
        },
        amountDue() {
            return this.subTotal + this.salesTax;
        },
    },
    components: {
        textBlock,
        textLink,
    },
};
</script>

<style lang="scss">
.cart {
    h5 {
        border-bottom: 1px solid $gray-500;
        color: $black;
    }
    .border-bottom {
        color: $gray;
    }
    .label {
        font-weight: 500;
    }
    .amount-due {
        color: $green;
    }
    .price-table {
        max-height: 0;
        transition: all 350ms ease-in;
        overflow: hidden;
        div {
            display: flex;
            justify-content: space-between;
            padding: 0.5rem 1.5rem;
            &:nth-child(odd) {
                background-color: #f5f5f5;
            }
            &:nth-last-child(-n + 3) {
                background-color: #e3f2ea;
            }
            &:last-child {
                background-color: #0c7e47;
                color: #ffffff;
            }
        }
        .vaps {
            background-color: #f5f5f5;
            padding-left: 2.5rem;
            align-items: center;
            span {
                display: flex;
                width: 33.33333%;
                &:nth-child(2) {
                    justify-content: flex-end;
                }
                &:last-child {
                    justify-content: flex-end;
                }
            }
        }
        .package-type,
        .service-type {
            //background-color: #f5f5f5;
            align-items: center;
        }
        .sub-total,
        .sales-tax,
        .amount-due {
            font-weight: 500;
        }
        .sub-total {
            border-top: 1px solid #0c7e47;
        }
        .service-type {
            // background-color: #f5f5f5;
            .text-block {
                background: transparent;
                margin-top: 0;
                padding: 0;
            }
        }
    }
    .vin-toggle {
        &:after {
            content: "";
            transition: all 0.5s ease;
            background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 8.9' xml:space='preserve'%3e%3cpath d='M8 8.9c-.2 0-.5-.1-.6-.3L.3 1.5C.1 1.4 0 1.1 0 .9 0 .7.1.4.3.3.4.1.7 0 .9 0c.2 0 .5.1.6.3L8 6.7 14.5.2c.1-.1.4-.2.6-.2.2 0 .5.1.6.3s.3.4.3.6c0 .2-.1.5-.3.6L8.6 8.6c-.1.2-.4.3-.6.3z' fill='%231474a2'/%3e%3c/svg%3e");
            background-repeat: no-repeat;
            background-position: right center;
            width: 16px;
            height: 9px;
            display: inline-flex;
            position: relative;
            right: 0.75rem;
            margin: 1rem 0 1rem 1rem;
            cursor: pointer;
        }
        &.active:after {
            transform: rotate(180deg);
        }
        &.active + .price-table {
            max-height: 650px;
            transition: all 350ms ease-in;
            overflow: hidden;
        }
    }
}
</style>
