/** @odoo-module **/

import publicWidget from "@web/legacy/js/public/public_widget";
import { jsonrpc } from "@web/core/network/rpc_service";

publicWidget.registry.Dine360SelfOrder = publicWidget.Widget.extend({
    selector: '#self_order_app',
    events: {
        'input #product_search': '_onSearchInput',
        'click #view_cart_btn': '_onViewCartClick',
        'click #submit_order_btn': '_onSubmitOrderClick',
        'click [data-category]': '_onCategoryClick',
        'click .add-to-cart-btn': '_onAddToCartClick',
        'click .increase-qty': '_onIncreaseQtyClick',
        'click .decrease-qty': '_onDecreaseQtyClick',
        'click .service-select': '_onServiceSelectClick',
    },

    init: function () {
        this._super.apply(this, arguments);
        this.config = {};
        this.state = {
            products: [],
            cart: [],
            activeCategory: 'all',
            searchTerm: '',
        };
    },

    start: async function () {
        await this._super.apply(this, arguments);
        const dataEl = this.el.querySelector('#self_order_data');
        if (dataEl) {
            this.config.tableId = dataEl.dataset.tableId;
            this.config.tableName = dataEl.dataset.tableName;
        }

        try {
            const products = await jsonrpc('/dine360/self_order/products', {});
            this.state.products = products;
            this._renderCategories();
            this._renderProducts();
            this.$('#loading_overlay').addClass('d-none');
            this.$('#self_order_content').removeClass('d-none');
        } catch (e) {
            console.error("Failed to load products", e);
            alert("Error connecting to server. Please try again later.");
        }
    },

    _renderCategories: function () {
        const categories = ['all', ...new Set(this.state.products.map(p => p.pos_categ_name))];
        const html = categories.map(cat => `
            <button class="btn btn-sm ${this.state.activeCategory === cat ? 'btn-warning fw-bold shadow-sm' : 'btn-white border'} rounded-pill px-3 py-2" data-category="${cat}">
                ${cat === 'all' ? 'All Items' : cat}
            </button>
        `).join('');
        this.$('#category_filter').html(html);
    },

    _renderProducts: function () {
        let filtered = this.state.products;
        if (this.state.activeCategory !== 'all') {
            filtered = filtered.filter(p => p.pos_categ_name === this.state.activeCategory);
        }
        if (this.state.searchTerm) {
            const term = this.state.searchTerm.toLowerCase();
            filtered = filtered.filter(p => p.display_name.toLowerCase().includes(term));
        }

        const html = filtered.map(p => `
            <div class="col-6 col-md-4 col-lg-3">
                <div class="card h-100 border-0 shadow-sm product-card transition-all" data-id="${p.id}">
                    <div class="position-relative">
                        <img src="${p.image_url}" class="card-img-top rounded-top-4" alt="${p.display_name}" style="height: 140px; object-fit: cover; opacity: 1;"/>
                        <div class="position-absolute bottom-0 end-0 p-1">
                            <button class="btn btn-warning btn-sm rounded-circle add-to-cart-btn shadow" style="width: 32px; height: 32px; padding: 0;">
                                <i class="fa fa-plus"/>
                            </button>
                        </div>
                    </div>
                    <div class="card-body p-3">
                        <div class="fw-bold text-dark small mb-1 text-truncate">${p.display_name}</div>
                        <div class="d-flex justify-content-between align-items-center">
                            <span class="fw-bold text-primary">$${p.list_price.toFixed(2)}</span>
                            ${p.is_kitchen_item ? '<i class="fa fa-fire text-danger small opacity-50"/>' : ''}
                        </div>
                    </div>
                </div>
            </div>
        `).join('');
        this.$('#product_list').html(html);
    },

    _onCategoryClick: function (ev) {
        this.state.activeCategory = $(ev.currentTarget).data('category');
        this._renderCategories();
        this._renderProducts();
    },

    _onAddToCartClick: function (ev) {
        ev.stopPropagation();
        const card = $(ev.currentTarget).closest('.product-card');
        const productId = parseInt(card.data('id'));
        const product = this.state.products.find(p => p.id === productId);
        const existing = this.state.cart.find(item => item.product_id === productId);
        if (existing) {
            existing.qty++;
        } else {
            this.state.cart.push({
                product_id: product.id,
                display_name: product.display_name,
                price_unit: product.list_price,
                qty: 1
            });
        }
        this._updateCartUI();
    },

    _updateCartUI: function () {
        const count = this.state.cart.reduce((acc, item) => acc + item.qty, 0);
        const total = this.state.cart.reduce((acc, item) => acc + (item.qty * item.price_unit), 0);

        this.$('#cart_count').text(count);
        this.$('#cart_total').text(`$${total.toFixed(2)}`);

        const $footerCart = this.$('#footer_cart');
        if (count > 0) {
            $footerCart.removeClass('d-none');
            setTimeout(() => $footerCart.css('transform', 'translateY(0)'), 10);
        } else {
            $footerCart.css('transform', 'translateY(100%)');
            setTimeout(() => $footerCart.addClass('d-none'), 300);
        }
    },

    _onSearchInput: function (ev) {
        this.state.searchTerm = ev.target.value;
        this._renderProducts();
    },

    _onViewCartClick: function () {
        this._renderCartModal();
        if (!this.cartModal) {
            this.cartModal = new bootstrap.Modal(this.el.querySelector('#cart_modal'));
        }
        this.cartModal.show();
    },

    _renderCartModal: function () {
        const total = this.state.cart.reduce((acc, item) => acc + (item.qty * item.price_unit), 0);

        const html = this.state.cart.map((item, index) => `
            <div class="d-flex align-items-center mb-4 cart-item">
                <div class="flex-grow-1">
                    <div class="fw-bold mb-1">${item.display_name}</div>
                    <div class="text-primary fw-bold">$${(item.qty * item.price_unit).toFixed(2)}</div>
                </div>
                <div class="d-flex align-items-center gap-2 bg-light rounded-pill p-1 border">
                    <button class="btn btn-sm btn-white rounded-circle shadow-sm decrease-qty" data-index="${index}" style="width:28px; height:28px; padding:0;">-</button>
                    <span class="px-2 fw-bold" style="min-width: 20px; text-align:center;">${item.qty}</span>
                    <button class="btn btn-sm btn-white rounded-circle shadow-sm increase-qty" data-index="${index}" style="width:28px; height:28px; padding:0;">+</button>
                </div>
            </div>
        `).join('');

        this.$('#cart_items_list').html(html);
        this.$('#checkout_subtotal').text(`$${total.toFixed(2)}`);
        this.$('#checkout_total').text(`$${total.toFixed(2)}`);
    },

    _onIncreaseQtyClick: function (ev) {
        const index = $(ev.currentTarget).data('index');
        this.state.cart[index].qty++;
        this._renderCartModal();
        this._updateCartUI();
    },

    _onDecreaseQtyClick: function (ev) {
        const index = $(ev.currentTarget).data('index');
        this.state.cart[index].qty--;
        if (this.state.cart[index].qty <= 0) {
            this.state.cart.splice(index, 1);
        }
        if (this.state.cart.length === 0 && this.cartModal) {
            this.cartModal.hide();
        }
        this._renderCartModal();
        this._updateCartUI();
    },

    _onServiceSelectClick: function (ev) {
        const $label = $(ev.currentTarget);
        this.$('.service-select').removeClass('active border-warning bg-warning-light');
        $label.addClass('active border-warning bg-warning-light');
    },

    _onSubmitOrderClick: async function () {
        const $btn = this.$('#submit_order_btn');
        const originalText = $btn.html();

        $btn.prop('disabled', true);
        $btn.html('<span class="spinner-border spinner-border-sm me-2"/>Sending...');

        const fulfilmentType = this.$('input[name="fulfilment"]:checked').val() || 'dine_in';

        const orderData = {
            table_id: this.config.tableId,
            fulfilment_type: fulfilmentType,
            lines: this.state.cart
        };

        try {
            const response = await jsonrpc('/dine360/self_order/submit_order', { order_data: orderData });
            if (response.success) {
                if (this.cartModal) this.cartModal.hide();
                this.state.cart = [];
                this._updateCartUI();

                // Success View
                this.$('#self_order_content').html(`
                    <div class="text-center py-5">
                        <div class="mb-4">
                            <div class="bg-success text-white d-inline-flex align-items-center justify-content-center rounded-circle shadow-lg" style="width: 100px; height: 100px;">
                                <i class="fa fa-check fa-4x"/>
                            </div>
                        </div>
                        <h2 class="fw-bold mb-3">Order Received!</h2>
                        <p class="text-muted mb-4 px-4">${response.message}</p>
                        <div class="bg-white p-4 rounded-4 shadow-sm mb-4">
                            <div class="small text-muted mb-1">Order Number</div>
                            <div class="h4 fw-bold text-dark mb-0">${response.order_name}</div>
                        </div>
                        <button onclick="window.location.reload()" class="btn btn-dark btn-lg px-5 rounded-pill shadow">
                            Order More Items
                        </button>
                    </div>
                `);
            } else {
                alert(response.error || "Order submission failed");
            }
        } catch (e) {
            console.error(e);
            alert("Connection lost. Please check your internet.");
        } finally {
            $btn.prop('disabled', false);
            $btn.html(originalText);
        }
    }
});

return publicWidget.registry.Dine360SelfOrder;
