/**
 * WarehousesSection.js — مدیریت انبارها (با LocationPicker)
 */
import SectionBase from "../../accounting/SectionBase.js";
import LocationPicker from "../../gis/components/LocationPicker.js";

const WH_TYPES = { main: "انبار اصلی", scrap: "ضایعات", consignment: "امانت", project: "پروژه" };

export default class WarehousesSection extends SectionBase {

    async template() {
        return `
        <div class="acc-section-wrap">
            <div class="acc-toolbar">
                <h2 class="acc-section-title">🏭 انبارها</h2>
                <div style="display:flex;gap:8px;">
                    <button class="acc-btn acc-btn--primary" data-ref="addBtn">➕ انبار جدید</button>
                    <button class="acc-btn acc-btn--secondary" data-ref="refreshBtn">🔄</button>
                </div>
            </div>
            <div data-ref="wrap"><div class="acc-loading">⏳ بارگذاری...</div></div>
        </div>`;
    }

    async afterRender() {
        await this._load();
        this.on(this.ref("refreshBtn"), "click", () => this._load());
        this.on(this.ref("addBtn"),     "click", () => this._openModal());
    }

    async _load() {
        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res = await this.api.get("/inv/warehouses");
            const rows = res?.data ?? [];
            if (!rows.length) { this.ref("wrap").innerHTML = `<div class="acc-empty">انباری ثبت نشده</div>`; return; }
            this.ref("wrap").innerHTML = `
            <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:16px;padding:4px;">
                ${rows.map(w => `
                <div class="inv-wh-card" style="border:1px solid #e2e8f0;border-radius:10px;padding:16px;">
                    <div style="display:flex;justify-content:space-between;align-items:start;">
                        <div>
                            <div style="font-weight:700;font-size:15px;">🏭 ${this.escape(w.name)}</div>
                            <div style="font-size:11px;color:#64748b;margin-top:2px;">${WH_TYPES[w.type] ?? w.type} | کد: ${this.escape(w.code)}</div>
                        </div>
                        <div style="display:flex;gap:4px;">
                            <button class="acc-btn acc-btn--xs" data-edit="${w.id}">✏️</button>
                            <button class="acc-btn acc-btn--xs" data-loc="${w.id}" data-name="${this.escape(w.name)}" style="background:#dbeafe;color:#1e40af;">📍</button>
                        </div>
                    </div>
                    ${w.location     ? `<div style="font-size:12px;color:#475569;margin-top:8px;">📍 ${this.escape(w.location)}</div>` : ""}
                    ${w.manager_name ? `<div style="font-size:12px;color:#475569;margin-top:4px;">👤 ${this.escape(w.manager_name)}</div>` : ""}
                    <div style="display:flex;gap:12px;margin-top:12px;font-size:13px;">
                        <div><b style="color:#3b82f6;">${this.escape(String(w.product_count ?? 0))}</b> قلم</div>
                        <div><b style="color:#10b981;">${this._fmt(w.total_value ?? 0)}</b> ﷼</div>
                    </div>
                </div>`).join("")}
            </div>`;
            this.ref("wrap").querySelectorAll("[data-edit]").forEach(btn =>
                btn.addEventListener("click", async () => {
                    const res2 = await this.api.get("/inv/warehouses");
                    const w = (res2?.data ?? []).find(x => x.id == btn.dataset.edit);
                    if (w) this._openModal(w);
                })
            );
            this.ref("wrap").querySelectorAll("[data-loc]").forEach(btn =>
                btn.addEventListener("click", () => LocationPicker.openModal({
                    api: this.api, entityType: 'warehouse',
                    entityId: parseInt(btn.dataset.loc), entityName: btn.dataset.name,
                }))
            );
        } catch { this.ref("wrap").innerHTML = `<div class="acc-error">❌ خطا</div>`; }
    }

    _openModal(w = null) {
        const isEdit = !!w;
        const typeOpts = Object.entries(WH_TYPES).map(([k,v]) =>
            `<option value="${k}" ${w?.type === k ? "selected" : ""}>${v}</option>`
        ).join("");

        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:420px;">
            <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(w?.code ?? "")}">
                    </div>
                    <div class="acc-form-group"><label>نام *</label>
                        <input name="name" required value="${this.escape(w?.name ?? "")}">
                    </div>
                </div>
                <div class="acc-form-group"><label>نوع انبار</label>
                    <select name="type">${typeOpts}</select>
                </div>
                <div class="acc-form-group"><label>مکان / آدرس</label>
                    <input name="location" value="${this.escape(w?.location ?? "")}">
                </div>
                <div class="acc-form-group"><label>مسئول انبار</label>
                    <input name="manager_name" value="${this.escape(w?.manager_name ?? "")}">
                </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 {
                if (isEdit) await this.api.put(`/inv/warehouses/${w.id}`, body);
                else        await this.api.post("/inv/warehouses", body);
                close(); this._toast("✅ انبار ذخیره شد"); this._load();
            } 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);
    }
}
