/** @odoo-module */

import { registry } from "@web/core/registry";
import { KanbanController } from "@web/views/kanban/kanban_controller";
import { kanbanView } from "@web/views/kanban/kanban_view";
import { onWillUnmount } from "@odoo/owl";
import { useService } from "@web/core/utils/hooks";

export class KdsKanbanController extends KanbanController {
    setup() {
        super.setup();
        console.log("[KDS Controller] Setup");

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

        const kdsChannel = "kds_channel";

        if (this.busService) {
            console.log(`[KDS Controller] Subscribing to channel: ${kdsChannel}`);
            this.busService.addChannel(kdsChannel);

            const handler = this._onKdsNotification.bind(this);
            this.busService.addEventListener("notification", handler);

            onWillUnmount(() => {
                if (this.busService) {
                    this.busService.removeEventListener("notification", handler);
                }
            });
        }
    }

    _onKdsNotification(event) {
        // console.log("[KDS Controller] Notification received:", event);

        const notifications = event.detail || [];
        let shouldReload = false;

        for (const notif of notifications) {
            // console.log("[KDS Controller] Processing notification:", notif);

            if (notif.type === "kds_new_order") {
                console.log("[KDS Controller] New order notification:", notif.payload);

                // Show notification to user
                if (this.notification) {
                    const payload = notif.payload;
                    this.notification.add(
                        `New Order: ${payload.qty}x ${payload.product_name} - ${payload.table_name || 'Web/Takeaway'}`,
                        {
                            title: "Kitchen Display",
                            type: "info",
                        }
                    );
                }

                shouldReload = true;
            }
        }

        if (shouldReload) {
            // Reload the view to show the new order
            // Adding a small delay to ensure the transaction is fully committed and indexed
            console.log("[KDS Controller] New order received. Reloading view in 1.5s...");
            setTimeout(async () => {
                try {
                    await this.model.load();
                    console.log("[KDS Controller] View reloaded. Current record count:", this.model.root.count);

                    // Force a re-render if the view still thinks it's empty
                    if (this.model.root.count > 0) {
                        this.render();
                    }
                } catch (error) {
                    console.error("[KDS Controller] Error during reload:", error);
                }
            }, 1500);
        }
    }
}

export const kdsKanbanView = {
    ...kanbanView,
    Controller: KdsKanbanController,
};

registry.category("views").add("kds_kanban", kdsKanbanView);

console.log("[KDS Backend] kds_backend.js loaded (JS Class mode - manual services)");
