/**
 * DimensionsSection.js — ابعاد (نمای تودرتو: هر سه سطح با هم)
 *   گروه (PARTY/...) ← بُعد (مشتری) ← مقدار (مشتری الف)
 * هر سطح inline: افزودن/ویرایش/حذف.
 */

import SectionBase from "../SectionBase.js";
const BaseView = SectionBase;

const DATA_TYPES = ["STRING", "INT", "BIGINT", "DECIMAL"];

export default class DimensionsSection extends BaseView {

    static title = "";

    constructor(props = {}) {
        super(props);
        this.api   = props.api;
        this._tree = [];
    }

    async template() {
        return `
            <div class="event-toolbar">
                <button class="acc-btn acc-btn--primary acc-btn--sm" data-act="add-group">+ گروه جدید</button>
                <button class="acc-btn acc-btn--secondary acc-btn--sm" data-ref="reloadBtn">🔄 بازخوانی</button>
                <span style="font-size:12px;color:#94a3b8;margin-right:auto;">گروه ← بُعد ← مقدار</span>
            </div>
            <div style="background:#f0fdf4;border:1px solid #bbf7d0;border-radius:10px;padding:10px 14px;
                        margin-bottom:14px;font-size:12px;color:#166534;line-height:1.7;">
                <strong>📌 ساختار:</strong> هر <b>گروه</b> چند <b>بُعد</b> دارد (مثلاً گروهِ «طرف حساب» → بُعدِ «مشتری»)،
                و هر بُعد چند <b>مقدار</b> (مثلاً «مشتری الف»). بُعدها را در «سرفصل‌ها» به حساب‌ها وصل می‌کنی.
            </div>
            <div class="dim-tree" data-ref="tree"></div>
        `;
    }

    async afterRender() {
        this.on(this.ref("reloadBtn"), "click", () => this._load());
        // event delegation برای کلِ درخت + دکمهٔ گروهِ جدید
        this.on(this.container, "click", e => this._onClick(e));
        await this._load();
    }

    async _load() {
        const tree = this.ref("tree");
        tree.innerHTML = `<div class="acc-loading"><div class="acc-spinner"></div>در حال بارگذاری...</div>`;
        try {
            const res = await this.api.get("/accounting/dimension-tree");
            this._tree = res?.data ?? [];
            this._render();
        } catch (e) {
            tree.innerHTML = `<div class="acc-error">خطا: ${this.escape(e?.message ?? "")}</div>`;
        }
    }

    _render() {
        const tree = this.ref("tree");
        if (!this._tree.length) {
            tree.innerHTML = `<div class="acc-empty">گروهی نیست. «+ گروه جدید» را بزنید.</div>`;
            return;
        }
        tree.innerHTML = this._tree.map(g => this._groupHtml(g)).join("");
    }

    _groupHtml(g) {
        const dims = g.dimensions || [];
        return `
            <div class="dim-grp">
                <div class="dim-grp__head">
                    <span class="dim-grp__name">🗂️ ${this.escape(g.group_name)}
                        <small style="font-family:monospace;color:#94a3b8;">${this.escape(g.group_code)}</small>
                        <small style="color:#94a3b8;">(${dims.length} بُعد)</small>
                    </span>
                    <span class="dim-actions">
                        <button class="acc-btn acc-btn--primary acc-btn--sm" data-act="add-dim" data-gid="${g.id}">+ بُعد</button>
                        <button class="acc-btn acc-btn--secondary acc-btn--sm" data-act="edit-group" data-id="${g.id}">ویرایش</button>
                        <button class="acc-btn acc-btn--danger acc-btn--sm" data-act="del-group" data-id="${g.id}">حذف</button>
                    </span>
                </div>
                <div class="dim-grp__body">
                    ${dims.length ? dims.map(d => this._dimHtml(d, g.id)).join("") : `<div class="dim-empty">بُعدی ندارد. «+ بُعد» را بزنید.</div>`}
                </div>
            </div>`;
    }

    _dimHtml(d, gid) {
        const vals = d.values || [];
        return `
            <div class="dim-def">
                <div class="dim-def__head">
                    <span class="dim-def__name">🏷️ ${this.escape(d.dim_name || d.name)}
                        <small style="font-family:monospace;color:#94a3b8;">${this.escape(d.dim_code)}</small>
                        <small style="color:#64748b;">· ${this.escape(d.data_type || "STRING")} · ${vals.length} مقدار</small>
                    </span>
                    <span class="dim-actions">
                        <button class="acc-btn acc-btn--primary acc-btn--sm" data-act="add-val" data-did="${d.id}">+ مقدار</button>
                        <button class="acc-btn acc-btn--secondary acc-btn--sm" data-act="edit-dim" data-id="${d.id}" data-gid="${gid}">ویرایش</button>
                        <button class="acc-btn acc-btn--danger acc-btn--sm" data-act="del-dim" data-id="${d.id}">حذف</button>
                    </span>
                </div>
                <div class="dim-vals">
                    ${vals.length ? vals.map(v => `
                        <div class="dim-val">
                            <span>▫️ ${this.escape(v.value_name)} <small style="font-family:monospace;color:#cbd5e1;">${this.escape(v.value_code)}</small></span>
                            <span class="dim-actions">
                                <button class="acc-btn acc-btn--secondary acc-btn--sm" data-act="edit-val" data-id="${v.id}" data-did="${d.id}">ویرایش</button>
                                <button class="acc-btn acc-btn--danger acc-btn--sm" data-act="del-val" data-id="${v.id}">حذف</button>
                            </span>
                        </div>`).join("") : `<div class="dim-empty">مقداری ندارد.</div>`}
                </div>
            </div>`;
    }

    /* ---------- delegation ---------- */
    _find(level, id) {
        if (level === "group") return this._tree.find(g => String(g.id) === String(id));
        for (const g of this._tree) {
            if (level === "dim") { const d = (g.dimensions || []).find(x => String(x.id) === String(id)); if (d) return d; }
            if (level === "val") for (const d of (g.dimensions || [])) { const v = (d.values || []).find(x => String(x.id) === String(id)); if (v) return v; }
        }
        return null;
    }

    _onClick(e) {
        const btn = e.target.closest("[data-act]");
        if (!btn) return;
        const act = btn.dataset.act;
        const id  = btn.dataset.id;
        if (act === "add-group")  this._openForm("groups", null, {});
        else if (act === "edit-group") this._openForm("groups", this._find("group", id), {});
        else if (act === "del-group")  this._delete("dimension-groups", id, this._find("group", id)?.group_name);
        else if (act === "add-dim")    this._openForm("dimensions", null, { group_id: btn.dataset.gid });
        else if (act === "edit-dim")   this._openForm("dimensions", this._find("dim", id), { group_id: btn.dataset.gid });
        else if (act === "del-dim")    this._delete("dimensions", id, this._find("dim", id)?.dim_name);
        else if (act === "add-val")    this._openForm("values", null, { dim_id: btn.dataset.did });
        else if (act === "edit-val")   this._openForm("values", this._find("val", id), { dim_id: btn.dataset.did });
        else if (act === "del-val")    this._delete("dimension-values", id, this._find("val", id)?.value_name);
    }

    /* ---------- form ---------- */
    _openForm(level, item, parent) {
        const isEdit = !!item;
        let fields = "";
        if (level === "groups") {
            fields = `
                <div class="acc-form-group"><label>کد گروه *</label>
                    <input name="group_code" value="${this.escape(item?.group_code ?? "")}" ${isEdit ? "readonly style='background:#f1f5f9'" : ""} placeholder="مثال: REGION" required></div>
                <div class="acc-form-group"><label>نام گروه *</label>
                    <input name="group_name" value="${this.escape(item?.group_name ?? "")}" required></div>
                <div class="acc-form-group"><label>توضیحات</label>
                    <input name="description" value="${this.escape(item?.description ?? "")}"></div>`;
        } else if (level === "dimensions") {
            fields = `
                <div class="acc-form-group"><label>نام بُعد *</label>
                    <input name="dim_name" value="${this.escape(item?.dim_name ?? item?.name ?? "")}" placeholder="مثال: مشتری" required></div>
                <div class="acc-form-group"><label>کد (اختیاری)</label>
                    <input name="dim_code" value="${this.escape(item?.dim_code ?? "")}" placeholder="خودکار اگر خالی"></div>
                <div class="acc-form-group"><label>نوع داده</label>
                    <select name="data_type">${DATA_TYPES.map(t => `<option value="${t}" ${item?.data_type === t ? "selected" : ""}>${t}</option>`).join("")}</select></div>`;
        } else {
            fields = `
                <div class="acc-form-group"><label>نام مقدار *</label>
                    <input name="value_name" value="${this.escape(item?.value_name ?? "")}" placeholder="مثال: مشتری الف" required></div>
                <div class="acc-form-group"><label>کد (اختیاری)</label>
                    <input name="value_code" value="${this.escape(item?.value_code ?? "")}" placeholder="خودکار اگر خالی"></div>`;
        }
        const titleTxt = (isEdit ? "ویرایش " : "افزودن ") + (level === "groups" ? "گروه" : level === "dimensions" ? "بُعد" : "مقدار");

        const overlay = document.createElement("div");
        overlay.className = "acc-modal-overlay";
        overlay.innerHTML = `
            <div class="acc-modal" style="max-width:460px;">
                <button class="acc-modal__close" type="button">✕</button>
                <div class="acc-modal__title">${titleTxt}</div>
                <form id="dim-form">${fields}
                    <div class="acc-modal__actions">
                        <button type="button" class="acc-btn acc-btn--secondary" data-action="cancel">انصراف</button>
                        <button type="submit" class="acc-btn acc-btn--primary" id="dim-submit">${isEdit ? "ذخیره" : "ایجاد"}</button>
                    </div>
                </form>
            </div>`;
        document.body.appendChild(overlay);
        const close = () => overlay.remove();
        overlay.querySelector(".acc-modal__close").addEventListener("click", close);
        overlay.querySelector("[data-action='cancel']").addEventListener("click", close);
        overlay.addEventListener("click", e => { if (e.target === overlay) close(); });

        overlay.querySelector("#dim-form").addEventListener("submit", async e => {
            e.preventDefault();
            const fd = new FormData(e.target);
            const body = {};
            fd.forEach((v, k) => body[k] = typeof v === "string" ? v.trim() : v);
            if (level === "dimensions" && parent.group_id) body.group_id = Number(parent.group_id);
            if (level === "values" && parent.dim_id)       body.dim_id   = Number(parent.dim_id);

            const base = level === "groups" ? "dimension-groups" : level === "dimensions" ? "dimensions" : "dimension-values";
            const btn = overlay.querySelector("#dim-submit");
            btn.disabled = true; btn.textContent = "در حال ذخیره...";
            try {
                if (isEdit) await this.api.put(`/accounting/${base}/${item.id}`, body);
                else        await this.api.post(`/accounting/${base}`, body);
                close();
                await this._load();
            } catch (err) {
                btn.disabled = false; btn.textContent = isEdit ? "ذخیره" : "ایجاد";
                alert("خطا: " + (err?.message ?? ""));
            }
        });
    }

    async _delete(base, id, name) {
        if (!confirm(`حذف «${name ?? ""}»؟`)) return;
        try {
            await this.api.delete(`/accounting/${base}/${id}`);
            await this._load();
        } catch (e) {
            alert("خطا در حذف: " + (e?.message ?? ""));
        }
    }
}
