export default class SearchableSelect {

    constructor({ api, source, valueField = "id", labelField = "name" }) {
        this.api = api;
        this.source = source;
        this.valueField = valueField;
        this.labelField = labelField;

        this.container = null;
        this.input = null;
        this.dropdown = null;

        this.records = [];
        this.value = null;
    }

    async mount(container, initialValue = null) {
        if (!container) return;

        this.container = document.createElement("div");
        this.container.className = "search-select";

        this.container.innerHTML = `
            <input type="text" class="search-select-input" placeholder="جستجو..." />
            <div class="search-select-dropdown"></div>
        `;

        container.appendChild(this.container);

        this.input = this.container.querySelector(".search-select-input");
        this.dropdown = this.container.querySelector(".search-select-dropdown");

        if (!this.input || !this.dropdown) return;

        await this.load();

        if (initialValue) this.setValue(initialValue);

        this.bindEvents();
    }

    async load() {
        if (!this.api || typeof this.api.get !== "function") return;
        const res = await this.api.get(this.source);
        this.records = res?.records || res?.data || res || [];
        this.renderList(this.records);
    }

    bindEvents() {
        if (!this.input || !this.dropdown) return;

        this.input.addEventListener("focus", () => {
            this.dropdown.style.display = "block";
        });

        this.input.addEventListener("input", () => {
            const q = (this.input.value || "").toLowerCase();
            const filtered = this.records.filter(r =>
                String(r[this.labelField] ?? "").toLowerCase().includes(q)
            );
            this.renderList(filtered);
        });

        document.addEventListener("click", (e) => {
            if (!this.container.contains(e.target)) {
                this.dropdown.style.display = "none";
            }
        });
    }

    renderList(list) {
        if (!this.dropdown) return;

        this.dropdown.innerHTML = list.map(r => `
            <div class="search-select-item" data-id="${r[this.valueField]}">
                ${r[this.labelField]}
            </div>
        `).join("");

        const items = this.dropdown.querySelectorAll(".search-select-item");

        items.forEach(item => {
            item.onclick = () => {
                const id = item.dataset.id;
                const rec = list.find(r => String(r[this.valueField]) === id);
                this.value = id;
                if (rec) {
                    this.input.value = rec[this.labelField];
                }
                this.dropdown.style.display = "none";
            };
        });
    }

    setValue(id) {
        const r = this.records.find(x => String(x[this.valueField]) === String(id));
        if (r) {
            this.value = id;
            this.input.value = r[this.labelField];
        }
    }

    getValue() {
        return this.value;
    }
}
