/** @odoo-module */

import { Component, useState, onMounted, onWillUnmount } from "@odoo/owl";
import { ProductScreen } from "@point_of_sale/app/screens/product_screen/product_screen";
import { useService } from "@web/core/utils/hooks";
import { registry } from "@web/core/registry";

export class FaceRecognitionSidebar extends Component {
    static template = "pos_face_recognition.FaceRecognitionSidebar";

    setup() {
        this.pos = useService("pos");
        this.orm = useService("orm");
        console.log("FaceRecognitionSidebar setup");
        this.state = useState({
            matches: [],
            selectedCustomer: null,
            lastOrders: [],
            topProducts: [],
        });
        this.recognitionInterval = null;
        this.stream = null;

        onMounted(() => {
            this.startCamera();
        });

        // Cleanup interval and camera when component is destroyed
        onWillUnmount(() => {
            if (this.recognitionInterval) {
                clearInterval(this.recognitionInterval);
            }
            if (this.stream) {
                this.stream.getTracks().forEach(track => track.stop());
            }
        });
    }

    async startCamera() {
        console.log("startCamera called");
        try {
            const video = document.getElementById('face-rec-video');
            console.log("Video element found:", video);
            if (video) {
                this.stream = await navigator.mediaDevices.getUserMedia({ video: true });
                console.log("Camera stream obtained:", this.stream);
                video.srcObject = this.stream;

                // Start real-time recognition loop once camera is ready
                this.startRealTimeRecognition();
            } else {
                console.error("Video element not found!");
            }
        } catch (err) {
            console.error("Error accessing camera:", err);
        }
    }

    startRealTimeRecognition() {
        console.log("startRealTimeRecognition called");
        console.log("Server URL:", this.pos.config.pos_face_rec_server_url);

        if (!this.pos.config.pos_face_rec_server_url) {
            console.error("Face Recognition Server URL is not configured. Please configure it in POS Settings.");
            return;
        }

        // Capture frame every 3 seconds
        this.recognitionInterval = setInterval(() => {
            console.log("Recognition interval tick");
            this.captureAndSendFrame();
        }, 3000);
    }

    async captureAndSendFrame() {
        const video = document.getElementById('face-rec-video');
        if (!video) {
            console.error("Video element not found");
            return;
        }

        if (!this.pos.config.pos_face_rec_server_url) {
            console.error("Face Recognition Server URL is not configured");
            return;
        }

        const canvas = document.createElement('canvas');
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        canvas.getContext('2d').drawImage(video, 0, 0);
        // Convert to base64, remove header
        const imageData = canvas.toDataURL('image/jpeg').split(',')[1];

        try {
            const response = await fetch(this.pos.config.pos_face_rec_server_url + '/recognize', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ image: imageData }),
            });

            if (response.ok) {
                const result = await response.json();
                if (result.matches && result.matches.length > 0) {
                    // Filter matches (ensure only >= 60% probability)
                    const filteredMatches = result.matches.filter(match => match.probability >= 0.6);

                    // Enrich matches with partner phone numbers
                    this.state.matches = filteredMatches.map(match => {
                        const partner = this.pos.db.get_partner_by_id(match.id);
                        return {
                            ...match,
                            phone: partner ? partner.phone || partner.mobile : null
                        };
                    });
                } else {
                    this.state.matches = [];
                }
            }
        } catch (err) {
            console.error("Error sending frame to AI server:", err);
        }
    }

    async selectCustomer(match) {
        console.log("selectCustomer called with match:", match);
        const partner = this.pos.db.get_partner_by_id(match.id);
        console.log("Partner found in DB:", partner);
        if (partner) {
            this.state.selectedCustomer = partner;
            this.pos.get_order().set_partner(partner);
            console.log("Partner set to current order:", this.pos.get_order().get_partner());

            // Fetch details
            await this.fetchCustomerDetails(partner.id);
        } else {
            console.error("Partner not found for ID:", match.id);
        }
    }

    async fetchCustomerDetails(partnerId) {
        // Fetch last 2 orders with detailed information
        const orders = await this.orm.searchRead("pos.order",
            [['partner_id', '=', partnerId]],
            ['name', 'date_order', 'amount_total', 'state', 'lines'],
            { limit: 2, order: "date_order desc" }
        );

        // Fetch order lines for each order
        for (let order of orders) {
            if (order.lines && order.lines.length > 0) {
                const lines = await this.orm.searchRead("pos.order.line",
                    [['id', 'in', order.lines]],
                    ['product_id', 'qty', 'price_subtotal_incl', 'full_product_name'],
                    {}
                );
                // Add product names to lines
                order.lines = lines.map(line => ({
                    ...line,
                    product_name: line.full_product_name || (line.product_id && line.product_id[1]) || 'Unknown Product'
                }));
            } else {
                order.lines = [];
            }
        }

        this.state.lastOrders = orders;

        // Fetch top 3 products
        try {
            const topProducts = await this.orm.call("res.partner", "get_top_products", [partnerId]);
            console.log("Top products received:", topProducts);
            console.log("Type:", typeof topProducts);
            console.log("First product:", topProducts && topProducts[0]);

            // Ensure it's an array
            if (Array.isArray(topProducts)) {
                this.state.topProducts = topProducts;
            } else {
                console.error("topProducts is not an array:", topProducts);
                this.state.topProducts = [];
            }
        } catch (error) {
            console.error("Error fetching top products:", error);
            this.state.topProducts = [];
        }
    }
}

ProductScreen.components = {
    ...ProductScreen.components,
    FaceRecognitionSidebar,
};
