// Fusion Accounting - Account Report Search Bar
// Copyright (C) 2026 Nexa Systems Inc.

import { Component, useRef, useState, onMounted } from "@odoo/owl";

/**
 * AccountReportSearchBar - Text search input for filtering report lines
 * by name or content within the currently displayed report.
 */
export class AccountReportSearchBar extends Component {
    static template = "fusion_accounting.AccountReportSearchBar";
    static props = {
        initialQuery: { type: String, optional: true },
    };

    setup() {
        this.searchText = useRef("search_bar_input");
        this.controller = useState(this.env.controller);

        onMounted(() => {
            if (this.props.initialQuery) {
                this.searchText.el.value = this.props.initialQuery;
                this.search();
            }
        });
    }

    //------------------------------------------------------------------------------------------------------------------
    // Search
    //------------------------------------------------------------------------------------------------------------------
    search() {
        const inputText = this.searchText.el.value.trim();
        const query = inputText.toLowerCase();
        const linesIDsMatched = [];

        if (query.length) {
            for (const line of this.controller.lines) {
                const lineName = line.name.trim().toLowerCase();
                const match = (lineName.indexOf(query) !== -1);

                if (match) {
                    linesIDsMatched.push(line.id);
                }
            }
            this.controller.lines_searched = linesIDsMatched;
            this.controller.updateOption("filter_search_bar", inputText);
        } else {
            delete this.controller.lines_searched;
            this.controller.deleteOption("filter_search_bar");
        }        
    }
}
