/** @odoo-module */

import { registry } from "@web/core/registry";
import { useService } from "@web/core/utils/hooks";
import { Component, useState, onMounted, onWillUnmount } from "@odoo/owl";
import { usePos } from "@point_of_sale/app/store/pos_hook";

console.log("[OnlineOrders] Module loading...");

export class OnlineOrdersScreen extends Component {
    static template = "dine360_online_orders.OnlineOrdersScreen";

    setup() {
        try {
            console.log("[OnlineOrders] Setup starting...");
            this.pos = usePos();

            // Direct access to services to avoid 'methods is not iterable' error
            this.orm = this.env.services.orm;
            this.notification = this.env.services.pos_notification;
            this.busService = this.env.services.bus_service;

            this.state = useState({
                orders: [],
                loading: true,
                selectedOrder: null,
                confirmingId: null,
                error: null,
            });

            console.log("[OnlineOrders] Services obtained:", {
                hasOrm: !!this.orm,
                hasNotif: !!this.notification,
                hasBus: !!this.busService
            });

            // Subscribe to bus notifications for real-time updates
            const channel = `online_orders_${this.pos.config.id}`;
            console.log("[OnlineOrders] Subscribing to channel:", channel);

            if (this.busService) {
                this.busService.addChannel(channel);
                this._notifHandler = this._onNotification.bind(this);
                this.busService.addEventListener("notification", this._notifHandler);
            }
        } catch (err) {
            console.error("[OnlineOrders] Setup Error:", err);
        }

        onMounted(() => {
            this.loadOnlineOrders();
            // Auto-refresh every 30 seconds
            this._refreshInterval = setInterval(() => {
                this.loadOnlineOrders();
            }, 30000);
        });

        onWillUnmount(() => {
            if (this._refreshInterval) {
                clearInterval(this._refreshInterval);
            }
            if (this.busService && this._notifHandler) {
                this.busService.removeEventListener("notification", this._notifHandler);
            }
        });
    }

    _onNotification(event) {
        const notifications = event.detail || [];
        for (const notif of notifications) {
            if (notif.type === "new_online_order") {
                console.log("[OnlineOrders] New order received!", notif.payload);
                this.notification.add(
                    `New Online Order from ${notif.payload.customer_name} - ${this.env.utils.formatCurrency(notif.payload.amount_total)}`
                );
                this.loadOnlineOrders();
            }
            if (notif.type === "online_order_confirmed" || notif.type === "online_order_rejected") {
                this.loadOnlineOrders();
            }
        }
    }

    async loadOnlineOrders() {
        try {
            this.state.loading = true;
            this.state.error = null;
            const orders = await this.orm.call(
                "pos.order",
                "get_online_orders",
                [this.pos.config.id]
            );
            this.state.orders = orders;
            this.state.loading = false;
            console.log("[OnlineOrders] Loaded", orders.length, "orders");
        } catch (error) {
            console.error("[OnlineOrders] Error loading orders:", error);
            this.state.loading = false;
            this.state.error = "Failed to load orders. Please check your connection.";
        }
    }

    selectOrder(order) {
        this.state.selectedOrder = order;
    }

    async confirmOrder(orderId) {
        try {
            this.state.confirmingId = orderId;
            this.state.error = null;
            await this.orm.call(
                "pos.order",
                "action_confirm_online_order",
                [[orderId]]
            );
            this.notification.add("Order confirmed and sent to kitchen! 🍳");
            // Remove from list
            this.state.orders = this.state.orders.filter(o => o.id !== orderId);
            if (this.state.selectedOrder && this.state.selectedOrder.id === orderId) {
                this.state.selectedOrder = null;
            }
            this.state.confirmingId = null;
        } catch (error) {
            console.error("[OnlineOrders] Confirm error:", error);
            this.notification.add("Failed to confirm order");
            this.state.error = "Failed to confirm order. It might have been modified.";
            this.state.confirmingId = null;
        }
    }

    async rejectOrder(orderId) {
        try {
            this.state.error = null;
            await this.orm.call(
                "pos.order",
                "action_reject_online_order",
                [[orderId]]
            );
            this.notification.add("Order has been rejected");
            this.state.orders = this.state.orders.filter(o => o.id !== orderId);
            if (this.state.selectedOrder && this.state.selectedOrder.id === orderId) {
                this.state.selectedOrder = null;
            }
        } catch (error) {
            console.error("[OnlineOrders] Reject error:", error);
            this.notification.add("Failed to reject order");
            this.state.error = "Failed to reject order.";
        }
    }

    formatDate(isoDate) {
        if (!isoDate) return "";
        const d = new Date(isoDate);
        return d.toLocaleString();
    }

    formatCurrency(amount) {
        return this.env.utils.formatCurrency(amount);
    }

    get orderCount() {
        return this.state.orders.length;
    }

    back() {
        if (this.pos.config.module_pos_restaurant && !this.pos.get_order()) {
            this.pos.showScreen("FloorScreen");
        } else {
            this.pos.showScreen("ProductScreen");
        }
    }
}

// Register the screen
registry.category("pos_screens").add("OnlineOrdersScreen", OnlineOrdersScreen);

console.log("[OnlineOrders] Screen registered!");
