/** @odoo-module */

import { jsonrpc } from "@web/core/network/rpc_service";

// We'll use a standard self-invoking function style since it's a public web module
(function () {
    'use strict';

    document.addEventListener('DOMContentLoaded', async () => {
        const app = document.querySelector('#self_order_app');
        if (!app) return;

        const dataEl = document.querySelector('#self_order_data');
        const config = {
            tableId: dataEl.dataset.tableId,
            tableName: dataEl.dataset.tableName,
        };

        const state = {
            products: [],
            cart: [],
            activeCategory: 'all',
            searchTerm: '',
        };

        // --- UI Elements ---
        const productList = document.querySelector('#product_list');
        const categoryFilter = document.querySelector('#category_filter');
        const cartCount = document.querySelector('#cart_count');
        const cartTotal = document.querySelector('#cart_total');
        const footerCart = document.querySelector('#footer_cart');
        const loadingOverlay = document.querySelector('#loading_overlay');
        const contentArea = document.querySelector('#self_order_content');

        // --- Init ---
        try {
            const products = await jsonrpc('/dine360/self_order/products', {});
            state.products = products;
            renderCategories();
            renderProducts();
            loadingOverlay.classList.add('d-none');
            contentArea.classList.remove('d-none');
        } catch (e) {
            console.error("Failed to load products", e);
            alert("Error connecting to server. Please try again later.");
        }

        // --- Functions ---
        function renderCategories() {
            const categories = ['all', ...new Set(state.products.map(p => p.pos_categ_name))];
            categoryFilter.innerHTML = categories.map(cat => `
                <button class="btn btn-sm ${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('');

            categoryFilter.querySelectorAll('button').forEach(btn => {
                btn.onclick = () => {
                    state.activeCategory = btn.dataset.category;
                    renderCategories();
                    renderProducts();
                };
            });
        }

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

            productList.innerHTML = 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>
                                <t t-if="p.is_kitchen_item">
                                    <i class="fa fa-fire text-danger small opacity-50"/>
                                </t>
                            </div>
                        </div>
                    </div>
                </div>
            `).join('');

            productList.querySelectorAll('.add-to-cart-btn').forEach(btn => {
                btn.onclick = (ev) => {
                    ev.stopPropagation();
                    const card = btn.closest('.product-card');
                    const productId = parseInt(card.dataset.id);
                    addToCart(productId);
                };
            });
        }

        function addToCart(productId) {
            const product = state.products.find(p => p.id === productId);
            const existing = state.cart.find(item => item.product_id === productId);
            if (existing) {
                existing.qty++;
            } else {
                state.cart.push({
                    product_id: product.id,
                    display_name: product.display_name,
                    price_unit: product.list_price,
                    qty: 1
                });
            }
            updateCartUI();
        }

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

            cartCount.textContent = count;
            cartTotal.textContent = `$${total.toFixed(2)}`;

            if (count > 0) {
                footerCart.classList.remove('d-none');
                setTimeout(() => footerCart.style.transform = 'translateY(0)', 10);
            } else {
                footerCart.style.transform = 'translateY(100%)';
                setTimeout(() => footerCart.classList.add('d-none'), 300);
            }
        }

        // --- Search ---
        document.querySelector('#product_search').oninput = (ev) => {
            state.searchTerm = ev.target.value;
            renderProducts();
        };

        // --- Cart Modal ---
        const cartModal = new bootstrap.Modal(document.getElementById('cart_modal'));
        document.querySelector('#view_cart_btn').onclick = () => {
            renderCartModal();
            cartModal.show();
        };

        function renderCartModal() {
            const list = document.querySelector('#cart_items_list');
            const total = state.cart.reduce((acc, item) => acc + (item.qty * item.price_unit), 0);

            list.innerHTML = 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('');

            document.querySelector('#checkout_subtotal').textContent = `$${total.toFixed(2)}`;
            document.querySelector('#checkout_total').textContent = `$${total.toFixed(2)}`;

            list.querySelectorAll('.increase-qty').forEach(btn => {
                btn.onclick = () => {
                    state.cart[btn.dataset.index].qty++;
                    renderCartModal();
                    updateCartUI();
                };
            });
            list.querySelectorAll('.decrease-qty').forEach(btn => {
                btn.onclick = () => {
                    const index = btn.dataset.index;
                    state.cart[index].qty--;
                    if (state.cart[index].qty <= 0) {
                        state.cart.splice(index, 1);
                    }
                    if (state.cart.length === 0) cartModal.hide();
                    renderCartModal();
                    updateCartUI();
                };
            });
        }

        // --- Submit Order ---
        document.querySelector('#submit_order_btn').onclick = async () => {
            const btn = document.querySelector('#submit_order_btn');
            const originalText = btn.innerHTML;

            btn.disabled = true;
            btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"/>Sending...';

            const fulfilmentType = document.querySelector('input[name="fulfilment"]:checked')?.value || 'dine_in';

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

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

                    // Success View
                    document.querySelector('#self_order_content').innerHTML = `
                        <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.disabled = false;
                btn.innerHTML = originalText;
            }
        };

        // Service Type Toggle
        document.querySelectorAll('.service-select').forEach(label => {
            label.onclick = () => {
                document.querySelectorAll('.service-select').forEach(l => l.classList.remove('active', 'border-warning', 'bg-warning-light'));
                label.classList.add('active', 'border-warning', 'bg-warning-light');
            };
        });
    });
})();
