/**
 * InvProductsSection.js — مدیریت محصولات انبار (با دسته‌بندی درختی)
 */
import SectionBase from "../../accounting/SectionBase.js";

const COSTING  = { avg: "میانگین موزون", fifo: "FIFO" };
const TRACKING = { none: "—", batch: "بچ/لات", serial: "سریال", both: "بچ + سریال" };

export default class InvProductsSection extends SectionBase {

    constructor(p) { super(p); this._categories = []; }

    async template() {
        return `
        <div class="acc-section-wrap" style="display:grid;grid-template-columns:220px 1fr;gap:16px;height:100%;">
            <!-- درخت دسته‌بندی -->
            <div style="border-left:1px solid #e2e8f0;padding-left:12px;">
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">
                    <b style="font-size:13px;">دسته‌بندی‌ها</b>
                    <button class="acc-btn acc-btn--xs" data-ref="addCatBtn">➕</button>
                </div>
                <div data-ref="catTree" style="font-size:12px;"></div>
            </div>

            <!-- لیست محصولات -->
            <div>
                <div class="acc-toolbar" style="margin-bottom:12px;">
                    <h3 data-ref="catTitle" style="margin:0;font-size:14px;">همه محصولات</h3>
                    <div style="display:flex;gap:8px;">
                        <input type="text" data-ref="search" placeholder="جستجو..." class="acc-input" style="width:180px;">
                        <button class="acc-btn acc-btn--primary" data-ref="addProdBtn">➕ محصول جدید</button>
                        <button class="acc-btn acc-btn--secondary" data-ref="refreshBtn">🔄</button>
                    </div>
                </div>
                <div data-ref="prodWrap"><div class="acc-loading">⏳ بارگذاری...</div></div>
            </div>
        </div>`;
    }

    async afterRender() {
        await this._loadCategories();
        await this._loadProducts();
        this.on(this.ref("refreshBtn"),  "click", () => this._loadProducts());
        this.on(this.ref("addProdBtn"),  "click", () => this._openProductModal());
        this.on(this.ref("addCatBtn"),   "click", () => this._openCategoryModal());
        this.on(this.ref("search"),      "input", () => this._filterProducts());
        this._activeCat = null;
    }

    async _loadCategories() {
        try {
            const res = await this.api.get("/inv/categories");
            this._categories = res?.data ?? [];
            this._renderCatTree();
        } catch {}
    }

    _renderCatTree() {
        const tree = this.ref("catTree");
        const cats = this._categories;
        const build = (parentId, level) => cats
            .filter(c => parseInt(c.parent_id) === parentId)
            .map(c => `
                <div style="padding:4px 0 4px ${level * 12}px;cursor:pointer;border-radius:4px;"
                     class="inv-cat-item ${this._activeCat === c.id ? 'inv-cat-item--active' : ''}"
                     data-cat-id="${c.id}" data-cat-name="${this.escape(c.name)}">
                    ${level > 0 ? "└ " : ""}${this.escape(c.name)}
                    <small style="color:#94a3b8;">(${c.product_count ?? 0})</small>
                </div>
                ${build(c.id, level + 1)}
            `).join("");

        tree.innerHTML = `
            <div style="padding:4px 0;cursor:pointer;font-weight:600;" data-cat-id="" data-cat-name="همه محصولات" class="inv-cat-item ${!this._activeCat ? 'inv-cat-item--active' : ''}">
                📁 همه محصولات
            </div>
            ${build(0, 0)}
        `;

        tree.querySelectorAll(".inv-cat-item").forEach(el => {
            el.addEventListener("click", () => {
                this._activeCat = el.dataset.catId ? parseInt(el.dataset.catId) : null;
                this.ref("catTitle").textContent = el.dataset.catName;
                tree.querySelectorAll(".inv-cat-item").forEach(e => e.classList.remove("inv-cat-item--active"));
                el.classList.add("inv-cat-item--active");
                this._loadProducts();
            });
        });
    }

    async _loadProducts() {
        const params = {};
        if (this._activeCat) params.category_id = this._activeCat;
        this.ref("prodWrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res = await this.api.get("/inv/products", params);
            this._rows = res?.data ?? [];
            this._renderProducts(this._rows);
        } catch {
            this.ref("prodWrap").innerHTML = `<div class="acc-error">❌ خطا</div>`;
        }
    }

    _renderProducts(rows) {
        if (!rows.length) {
            this.ref("prodWrap").innerHTML = `<div class="acc-empty">محصولی یافت نشد</div>`;
            return;
        }
        this.ref("prodWrap").innerHTML = `
        <table class="acc-table">
            <thead><tr><th>کد</th><th>نام</th><th>دسته</th><th>واحد</th><th>موجودی</th><th>قیمت‌گذاری</th><th>ردیابی</th><th>اقدام</th></tr></thead>
            <tbody>
            ${rows.map(r => `<tr>
                <td style="font-weight:600;">${this.escape(r.code)}</td>
                <td>${this.escape(r.name)}</td>
                <td><small>${this.escape(r.category_name ?? "—")}</small></td>
                <td>${this.escape(r.unit)}</td>
                <td style="color:${parseFloat(r.total_stock) > 0 ? "#1d4ed8" : "#94a3b8"};">${this._fmt(r.total_stock)}</td>
                <td><small>${COSTING[r.costing_method] ?? r.costing_method}</small></td>
                <td><small>${TRACKING[r.tracking] ?? r.tracking}</small></td>
                <td style="display:flex;gap:4px;">
                    <button class="acc-btn acc-btn--xs" data-edit="${r.id}">✏️</button>
                    <button class="acc-btn acc-btn--xs gis-btn--danger" data-del="${r.id}" ${parseFloat(r.total_stock) > 0 ? "disabled title='موجودی دارد'" : ""}>🗑️</button>
                </td>
            </tr>`).join("")}
            </tbody>
        </table>`;

        this.ref("prodWrap").querySelectorAll("[data-edit]").forEach(btn =>
            btn.addEventListener("click", () => {
                const row = this._rows.find(r => r.id == btn.dataset.edit);
                if (row) this._openProductModal(row);
            })
        );
        this.ref("prodWrap").querySelectorAll("[data-del]").forEach(btn =>
            btn.addEventListener("click", async () => {
                if (!confirm("حذف این محصول؟")) return;
                try {
                    await this.api.delete(`/inv/products/${btn.dataset.del}`);
                    this._toast("✅ حذف شد"); this._loadProducts();
                } catch(e) { alert("خطا: " + (e?.message ?? "")); }
            })
        );
    }

    _filterProducts() {
        const q = (this.ref("search")?.value ?? "").toLowerCase();
        if (!q) { this._renderProducts(this._rows ?? []); return; }
        this._renderProducts((this._rows ?? []).filter(r =>
            r.name.toLowerCase().includes(q) || (r.code ?? "").toLowerCase().includes(q)
        ));
    }

    _openProductModal(p = null) {
        const isEdit = !!p;
        const catOpts = this._categories.map(c =>
            `<option value="${c.id}" ${p?.category_id == c.id ? "selected" : ""}>${"—".repeat(c.level)} ${this.escape(c.name)}</option>`
        ).join("");

        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:520px;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">${isEdit ? "✏️ ویرایش" : "➕ محصول جدید"}</div>
            <form>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>کد *</label>
                        <input name="code" required value="${this.escape(p?.code ?? "")}">
                    </div>
                    <div class="acc-form-group"><label>نام *</label>
                        <input name="name" required value="${this.escape(p?.name ?? "")}">
                    </div>
                </div>
                <div class="acc-form-group"><label>دسته‌بندی</label>
                    <select name="category_id"><option value="">— بدون دسته —</option>${catOpts}</select>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>واحد اصلی</label>
                        <input name="unit" value="${this.escape(p?.unit ?? "عدد")}">
                    </div>
                    <div class="acc-form-group"><label>واحد دوم</label>
                        <input name="unit2" value="${this.escape(p?.unit2 ?? "")}">
                    </div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>روش قیمت‌گذاری</label>
                        <select name="costing_method">
                            <option value="avg"  ${p?.costing_method === "avg"  ? "selected" : ""}>میانگین موزون</option>
                            <option value="fifo" ${p?.costing_method === "fifo" ? "selected" : ""}>FIFO</option>
                        </select>
                    </div>
                    <div class="acc-form-group"><label>ردیابی</label>
                        <select name="tracking">
                            <option value="none"   ${p?.tracking === "none"   ? "selected" : ""}>بدون ردیابی</option>
                            <option value="batch"  ${p?.tracking === "batch"  ? "selected" : ""}>بچ / لات</option>
                            <option value="serial" ${p?.tracking === "serial" ? "selected" : ""}>سریال نامبر</option>
                            <option value="both"   ${p?.tracking === "both"   ? "selected" : ""}>هر دو</option>
                        </select>
                    </div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>حداقل موجودی</label>
                        <input name="min_stock" type="number" min="0" step="any" value="${p?.min_stock ?? 0}">
                    </div>
                    <div class="acc-form-group"><label>مقدار سفارش مجدد</label>
                        <input name="reorder_qty" type="number" min="0" step="any" value="${p?.reorder_qty ?? 0}">
                    </div>
                </div>
                <div class="acc-form-group"><label>توضیحات</label>
                    <textarea name="description" rows="2">${this.escape(p?.description ?? "")}</textarea>
                </div>
                <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">ذخیره</button>
                </div>
            </form>
        </div>`;

        document.body.appendChild(ov);
        const close = () => ov.remove();
        ov.querySelector(".acc-modal__close").addEventListener("click", close);
        ov.querySelector("[data-action=cancel]").addEventListener("click", close);
        ov.addEventListener("click", e => { if (e.target === ov) close(); });
        ov.querySelector("form").addEventListener("submit", async ev => {
            ev.preventDefault();
            const body = Object.fromEntries(new FormData(ev.target).entries());
            if (!body.category_id) delete body.category_id;
            const btn = ev.target.querySelector("[type=submit]");
            btn.disabled = true;
            try {
                if (isEdit) { await this.api.put(`/inv/products/${p.id}`, body); this._toast("✅ ویرایش شد"); }
                else        { await this.api.post("/inv/products", body);         this._toast("✅ محصول ثبت شد"); }
                close(); this._loadProducts();
            } catch(e) { alert("خطا: " + (e?.message ?? "")); btn.disabled = false; }
        });
    }

    _openCategoryModal() {
        const parentOpts = this._categories.map(c =>
            `<option value="${c.id}">${"—".repeat(c.level)} ${this.escape(c.name)}</option>`
        ).join("");
        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:380px;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">➕ دسته‌بندی جدید</div>
            <form>
                <div class="acc-form-group"><label>دسته والد</label>
                    <select name="parent_id"><option value="0">— سطح اول —</option>${parentOpts}</select>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>کد</label><input name="code"></div>
                    <div class="acc-form-group"><label>نام *</label><input name="name" required></div>
                </div>
                <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">ذخیره</button>
                </div>
            </form>
        </div>`;
        document.body.appendChild(ov);
        const close = () => ov.remove();
        ov.querySelector(".acc-modal__close").addEventListener("click", close);
        ov.querySelector("[data-action=cancel]").addEventListener("click", close);
        ov.addEventListener("click", e => { if (e.target === ov) close(); });
        ov.querySelector("form").addEventListener("submit", async ev => {
            ev.preventDefault();
            const body = Object.fromEntries(new FormData(ev.target).entries());
            const btn  = ev.target.querySelector("[type=submit]");
            btn.disabled = true;
            try {
                await this.api.post("/inv/categories", body);
                this._toast("✅ دسته ثبت شد");
                close(); await this._loadCategories();
            } catch(e) { alert("خطا: " + (e?.message ?? "")); btn.disabled = false; }
        });
    }

    _fmt(v) { return new Intl.NumberFormat("fa-IR").format(Math.round(Number(v ?? 0))); }
    escape(s) { return String(s ?? "").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"); }
    _toast(msg, bg = "#10b981") {
        const t = document.createElement("div");
        t.style.cssText = `position:fixed;bottom:24px;left:24px;background:${bg};color:#fff;padding:12px 20px;border-radius:10px;font-size:13px;font-weight:600;z-index:9999;`;
        t.textContent = msg; document.body.appendChild(t); setTimeout(() => t.remove(), 3000);
    }
}
