import { Component, Fragment, Event, Watch, Element, EventEmitter, Listen, State, h } from '@stencil/core';
import { Product } from '../../classes/product';
import { v4 as uuid } from 'uuid';
import { resolveAsset } from '../../classes/helpers';

@Component({
    tag: 'app-home',
    styleUrl: 'app-home.css',
    scoped: true,
})
export class AppHome {
    @State() currentPrice: number = 0;
    @State() currentStep: string = 'home';
    @State() box: BundleBox;
    @State() products: Product[] = [];
    @State() showSummary: boolean = false;
    @State() frequency: number = 4;

    @Event() toggleBurgerMenu: EventEmitter;
    @Event() progressStepChanged: EventEmitter;

    @Element() el: HTMLElement;

    readonly stages = ['home', 'box', 'products', 'frequency', 'basket'];

    @Listen('progressStepChanged', { target: 'body' })
    progressStepChangedHandler(step: CustomEvent<string>) {
        this.showSummary = false;

        if (step.detail) {
            var index = this.stages.indexOf(step.detail);
            this.currentStep = this.stages[index];
            return;
        }

        var currentStepIndex = this.stages.indexOf(this.currentStep);
        var nextStepIndex = this.stages[currentStepIndex + 1];

        this.currentStep = nextStepIndex;
    }

    @Watch('currentStep')
    changeProgress() {
        const mainWrapper = document.querySelector('#main-wrapper .content-wrapper');
        if (mainWrapper) {
            mainWrapper.scrollTop = 0;
        }
    }

    @Listen('boxChanged')
    boxChangedHandler(event: CustomEvent<BundleBox>) {
        this.box = event.detail;
        this.currentStep = 'products';
    }

    @Listen('productChanged')
    productChangeHandler(event: CustomEvent<Product>) {
        var productIndex = this.products.findIndex(obj => obj.id == event.detail.id);
        this.products[productIndex].quantity = event.detail.quantity;

        // update the object and the array to trigger updates
        this.products[productIndex] = { ...this.products[productIndex] };
        this.products = [...this.products];
        this.calculateTotal();
    }

    @Listen('toggleSummary')
    toggleSummaryHandler() {
        this.showSummary = !this.showSummary;
    }

    @Listen('frequencyUpdate')
    frequencyUpdateHandler(event: CustomEvent<number>) {
        this.frequency = event.detail;
    }

    componentWillLoad() {
        this.getProducts();
        this.calculateTotal();
    }

    getProducts() {
        this.products.push(new Product(uuid(), 'Fennel and Garlic Salami', 'Sliced award winning Fennel and Garlic Salami, our take on the classic Italian Finocchiona, typical of the Tuscany region.', resolveAsset('/assets/product-images/salami.jpg'), 300, 0, false));
        this.products.push(new Product(uuid(), 'N1 Soppressata Salami', 'A large fresh flavoured salami typical of Calabria in the South Western region of Italy', resolveAsset('/assets/product-images/salami.jpg'), 500, 0, false));
        this.products.push(new Product(uuid(), 'Salt and Pepper Salami', 'A simple all British pork salami with salt and tellicherry black pepper as well a little garlic, giving a great balanced flavour letting the quality of the meat shine.', resolveAsset('/assets/product-images/salami.jpg'), 500, 0, false));
        this.products.push(new Product(uuid(), 'Lomo', 'A simple air dried ham - using the eye of the pork loin, flavoured with garlic and Hungarian paprika.', resolveAsset('/assets/product-images/salami.jpg'), 750, 0, false));
        this.products.push(new Product(uuid(), 'Coppa', 'We make our Coppa real slow! Giving it as much time in our chamber as possible, up to 5 months to mature.', resolveAsset('/assets/product-images/salami.jpg'), 250, 0, false));
        this.products.push(new Product(uuid(), 'Bresaola', 'Sliced Bresaola cured with herbs, balsamic vinegar and red wine, which give a refreshing tang. It is a great way to experience British beef.', resolveAsset('/assets/product-images/salami.jpg'), 650, 0, false));
        this.products.push(new Product(uuid(), 'Nduja', 'Nduja is one of our most versatile and sexy British cured meats and is the perfect addition to almost every dish.', resolveAsset('/assets/product-images/nduja.jpg'), 1000, 0, true));
        this.products.push(new Product(uuid(), 'Pancetta (Unsliced)', 'Made from British Pork Belly, cured with pepper and rosemary and then hung and air dried in our maturation chamber for 10-12 weeks.', resolveAsset('/assets/product-images/pancetta.jpg'), 950, 0, true));
    }

    calculateTotal() {
        var total: number = 0;
        this.products.forEach(element => {
            total += element.price * element.quantity;
        });

        this.currentPrice = total;
    }

    renderSummaryBar() {
        if (this.showSummary) {
            return <order-summary products={this.products}></order-summary>;
        }
    }

    renderStatusBar() {
        if (this.currentStep == 'products' || this.currentStep == 'frequency') {
            return <status-bar summaryActive={this.showSummary} currentPrice={this.currentPrice}></status-bar>;
        } else {
            return (
                <footer class="py-3">
                    <div class="container">
                        <div class="row gy-2 justify-content-between align-items-center align-items-md-end">
                            <div class="col">
                                <img class="partner-logos" src={resolveAsset('/assets/partner-logos.png')} alt="Cobble Logo" />
                            </div>
                            <div class="col-auto">Lovingly prepared by Cobble Lane Cured.</div>
                        </div>
                    </div>
                </footer>
            );
        }
    }

    render() {
        var html;

        this.el.style.setProperty('--background-img', 'url(' + resolveAsset('/assets/paper-bg-min.png') + ')');

        switch (this.currentStep) {
            case 'home':
                return (
                    <div id="main-wrapper" class="wrapper h-100">
                        <div class="header-bar">
                            <div class="logo-wrapper">
                                <img class="logo" src={resolveAsset('/assets/club-logo.svg')} />
                                <span>Cobble Subscription Club</span>
                            </div>
                            <button class="burger-menu px-0" onClick={() => this.toggleBurgerMenu.emit(this)}>
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
                                    <path d="M3,6H21V8H3V6M3,11H21V13H3V11M3,16H21V18H3V16Z" />
                                </svg>
                            </button>
                        </div>
                        <side-bar></side-bar>
                        <progress-home></progress-home>
                    </div>
                );

            case 'box':
                html = <progress-box></progress-box>;
                break;

            case 'products':
                html = (
                    <Fragment>
                        <progress-products products={this.products}></progress-products>
                        {this.renderSummaryBar()}
                    </Fragment>
                );
                break;

            case 'frequency':
                html = (
                    <Fragment>
                        <progress-frequency frequency={this.frequency}></progress-frequency>
                        {this.renderSummaryBar()}
                    </Fragment>
                );
                break;

            case 'basket':
                var chosenProducts = this.products.filter(p => p.quantity > 0);
                html = <progress-basket products={chosenProducts} frequency={this.frequency} total={this.currentPrice}></progress-basket>;
                break;
        }

        return (
            <fragment>
                <div id="main-wrapper" class="wrapper">
                    <div class="content-wrapper">
                        <div class="top-bar">
                            <img class="logo" src={resolveAsset('/assets/club-logo.svg')} alt="Cobble Lane Cured Club" onClick={() => this.progressStepChanged.emit('home')} />
                        </div>
                        {html}
                    </div>
                    {this.renderStatusBar()}
                </div>
            </fragment>
        );
    }
}
