import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';
import { OrderService } from '../services/order.service';
import { ToastService } from '../services/toast.service';
import { ModalController } from '@ionic/angular';
import { InAppBrowserPage } from '../in-app-browser/in-app-browser.page';
import { MallService } from '../services/mall.service';
import * as moment from 'moment';

export type ICart = {
    orderedlist: Array<{
        mall_id: number,
        outlet_id: number,
        menuitem_id: number,
        quantity: number,
        pickup_time: string,
        take_away: boolean,
        order_status: boolean,
        total_price: number,
        soft_delete: boolean,
    }>
};

@Component({
    selector: 'app-cart',
    templateUrl: './cart.page.html',
    styleUrls: ['./cart.page.scss'],
})

export class CartPage implements OnInit {
    userCart: ICart = {
        orderedlist: []
    };
    show_order_details: boolean = false;
    cart_outlets: any = [];
    allMalls: any = [];
    tempPickupTime: any;
    showInstantMenu: boolean = false;
    temp_outlet_details: any;
    selectedTempMallId: string;
    show_promocodes: boolean = false;
    userInfo: any;
    mallPromoCodes: Array<any> = [];
    invoiceData: any;
    selected_promo: any = '';

    constructor(
        private location: Location,
        private orderService: OrderService,
        private toastService: ToastService,
        private router: Router,
        public modalController: ModalController,
        private mallService: MallService
    ) { }

    ngOnInit() {
        this.hideMenuButton();
        this.userInfo = JSON.parse(localStorage.userInfo)['User Info'];
    }

    ngOnDestroy() {
        this.showMenuButton();
    }

    ionViewDidEnter() {
        this.fetchCartItems();
        this.allMalls = JSON.parse(localStorage.getItem('malls'))
        // this.mallService.allMalls().then((response) => {
        //     this.allMalls = response;
        // }, (error) => {
        //     console.log(error);
        // });
    }

    fetchCartItems() {
        this.cart_outlets = [];

        if (localStorage.userCart) {
            this.userCart = JSON.parse(localStorage.userCart);
        } else {
            localStorage.userCart = JSON.stringify(this.userCart);
        }

        // this.cart_malls = this.userCart.orderedlist.map(order => order.mall_id);

        for (let i = 0; i < this.userCart.orderedlist.length; i += 1) {
            let tempOutlet = this.cart_outlets.find((outlet) => {
                return outlet.outlet_id === this.userCart.orderedlist[i].outlet_id &&
                    outlet.mall_id === this.userCart.orderedlist[i].mall_id
            });

            if (!tempOutlet) {
                this.cart_outlets.push({
                    outlet_id: this.userCart.orderedlist[i].outlet_id,
                    mall_id: this.userCart.orderedlist[i].mall_id
                })
            }
        }

        this.cart_outlets.forEach((cart) => {
            this.orderService.getPromoCodes(cart.mall_id).then((data) => {
                this.mallPromoCodes.push(data);

            }, (err) => console.log(err));
        });
    }

    hideMenuButton() {
        document.querySelector('.menu-icon-holder').classList.add('hide');
    }

    showMenuButton() {
        document.querySelector('.menu-icon-holder').classList.remove('hide');
    }

    checkIfTimeFeasible(oldTime, newTime) {
        return moment(newTime) > moment(oldTime);
    }

    getOutletDetails(cartOutlet: any) {
        let mall, outlet;

        mall = this.allMalls.find((mall) => {
            return mall.mall.mall_id === cartOutlet.mall_id;
        });

        if (mall) {
            return outlet = mall.mall.outlet.find((outlet) => {
                return outlet.outlet_id === cartOutlet.outlet_id;
            });
        }
    }

    getMallDetails(mallId: number) {
        return this.allMalls.find((mall) => {
            return mall.mall.mall_id === mallId;
        });
    }

    getItemDetails(item) {
        let mall, outlet, outletitem
        mall = this.allMalls.find((mall) => {
            return mall.mall.mall_id === item.mall_id;
        });

        if (mall) {
            outlet = mall.mall.outlet.find((outlet) => {
                return outlet.outlet_id === item.outlet_id;
            });
        }

        if (outlet) {
            return outletitem = outlet.menuitems.find((menu) => {
                return menu.menuitem_id === item.menuitem_id;
            });
        }
    }

    storeData() {
        localStorage.userCart = JSON.stringify(this.userCart);
    }

    getFormatterDateTime(date: any, format: string) {
        return moment(date).format(format);
    }

    back() {
        this.showMenuButton();
        this.storeData();
        this.location.back();
    }

    openInstantMenu(outlet) {
        this.selectedTempMallId = outlet.mall_id;
        this.showInstantMenu = true;
        this.temp_outlet_details = this.getOutletDetails(outlet);
    }

    isPresentInCart(outletId: number, itemId: number, tempMallId: number) {
        let item: any;

        item = this.userCart.orderedlist.find((order) => {
            return order.menuitem_id === itemId && order.outlet_id === outletId && order.mall_id === tempMallId;
        });

        return item ? item.quantity : 0;
    }

    incrementCartCount(outletId: number, itemId: number, tempMallId: number) {
        let outletitem = this.getItemDetailsByIds(outletId, itemId, tempMallId);

        if (outletitem) {
            let i = this.userCart.orderedlist.findIndex((order) => {
                return order.menuitem_id === itemId && order.outlet_id === outletId && order.mall_id === tempMallId;
            });

            this.userCart.orderedlist[i].quantity += 1;
            this.userCart.orderedlist[i].total_price = (outletitem.item_price - outletitem.item_discount) * this.userCart.orderedlist[i].quantity;
        }
    }

    decrementCartCount(outletId: number, itemId: number, tempMallId: number) {
        let outletitem = this.getItemDetailsByIds(outletId, itemId, tempMallId);

        if (outletitem) {
            let i = this.userCart.orderedlist.findIndex((order) => {
                return order.menuitem_id === itemId && order.outlet_id === outletId && order.mall_id === tempMallId;
            });

            if (this.userCart.orderedlist[i].quantity > 1) {
                this.userCart.orderedlist[i].quantity -= 1;
                this.userCart.orderedlist[i].total_price = (outletitem.item_price - outletitem.item_discount) * this.userCart.orderedlist[i].quantity;
            } else if (this.userCart.orderedlist[i].quantity === 1) {
                this.userCart.orderedlist.splice(i, 1);
                this.storeData();
                this.fetchCartItems();
            }
        }
    }

    getItemDetailsByIds(outletId: number, itemId: number, tempMallId: number) {
        let mall, outlet, outletitem;
        mall = this.allMalls.find((mall) => {
            return mall.mall.mall_id === tempMallId;
        });

        if (mall) {
            outlet = mall.mall.outlet.find((outlet) => {
                return outlet.outlet_id === outletId;
            });
        }

        if (outlet) {
            return outletitem = outlet.menuitems.find((menu) => {
                return menu.menuitem_id === itemId;
            });
        }
    }

    addToCart(outletId: number, itemId: number, tempMallId: number) {
        let outletitem = this.getItemDetailsByIds(outletId, itemId, tempMallId);
        if (outletitem) {
            this.userCart.orderedlist.push({
                mall_id: tempMallId,
                outlet_id: outletId,
                menuitem_id: itemId,
                quantity: 1,
                pickup_time: moment().add(moment.duration(outletitem.wait_duration).asMinutes(), 'minutes').format(),
                take_away: true,
                order_status: false,
                total_price: outletitem.item_price - outletitem.item_discount,
                soft_delete: false
            });
        }
    }

    getTotalCartAmount() {
        let total: number = 0, discountValue: number = 0

        this.userCart.orderedlist.forEach((order) => {
            total = order.total_price + total;
            discountValue = (total * this.selected_promo.offer_precentage/100)
        });

        if(!discountValue){
            return total
        }else{
            if(discountValue>=this.selected_promo.offersMaxcount){
                total = total-this.selected_promo.offersMaxcount
            }else{
                total = total-discountValue
            }
            return total
        }

    }

    placeOrder() {
        this.orderService.createOrder(this.userInfo.id, {
            soft_delete: false,
            orderedlist: this.userCart.orderedlist
        }).then(() => {
            this.toastService.presentToast("Order has been created", "success");
            localStorage.removeItem('userCart');
            this.router.navigate(['/profile']);
        }, () => {
            this.toastService.presentToast("Failed to create order!", "danger");
        });
    }

    requestInvoice() {
        let invoice_data = {
            "name": this.userInfo.name,
            "email": this.userInfo.email,
            "contact": this.userInfo.mobile,
            "total_amt": (this.getTotalCartAmount() + (this.getTotalCartAmount() * (18 / 100)) + 20),
            "description": "This payment is towards testing Invoice feature",
            "receipt": "#asdsdsdf",
            "email_notify": 1,
        };

        this.orderService.generateInvoice(invoice_data).then((data: any) => {
            this.invoiceData = data;
            this.presentModal(data.shorturl);
            
        }, (err) => {
            this.toastService.presentToast("Oops, something went wrong", "danger");
        });
    }


    async presentModal(url: string) {
        const modal = await this.modalController.create({
            component: InAppBrowserPage,
            componentProps: {
                url: url
            }
        });

        modal.onDidDismiss().then(() => {
            this.showMenuButton();

            this.orderService.getPaymentDetailsByOrderID(this.invoiceData.orderId).then((paymentDetails: any) => {
                if (paymentDetails.Status === "paid") {
                    this.placeOrder();
                } else {
                    this.toastService.presentToast("Payment Failed!", "danger");
                }
            });
        });

        return await modal.present();
    }

}
