/**
 * BatchesSection.js — مدیریت بچ / لات
 */
import SectionBase from "../../accounting/SectionBase.js";

export default class BatchesSection extends SectionBase {

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

    async template() {
        return `
        <div class="acc-section-wrap">
            <div class="acc-toolbar">
                <h2 class="acc-section-title">📦 بچ / لات</h2>
                <div style="display:flex;gap:8px;align-items:center;">
                    <select data-ref="prodFilter" class="acc-input" style="width:200px;">
                        <option value="">همه محصولات</option>
                    </select>
                    <button class="acc-btn acc-btn--warning" data-ref="expiringBtn">⏰ در حال انقضا</button>
                    <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._loadProducts();
        await this._load();
        this.on(this.ref("refreshBtn"),   "click",  () => this._load());
        this.on(this.ref("addBtn"),       "click",  () => this._openModal());
        this.on(this.ref("prodFilter"),   "change", () => this._load());
        this.on(this.ref("expiringBtn"),  "click",  () => this._loadExpiring());
    }

    async _loadProducts() {
        try {
            const res = await this.api.get("/inv/products");
            this._products = res?.data ?? [];
            const sel = this.ref("prodFilter");
            this._products.forEach(p => {
                const o = document.createElement("option"); o.value = p.id; o.textContent = p.name;
                sel.appendChild(o);
            });
        } catch {}
    }

    async _load() {
        const pid = this.ref("prodFilter")?.value;
        const params = pid ? { product_id: pid } : {};
        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res = await this.api.get("/inv/batches", params);
            this._renderTable(res?.data ?? []);
        } catch { this.ref("wrap").innerHTML = `<div class="acc-error">❌ خطا</div>`; }
    }

    async _loadExpiring() {
        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res = await this.api.get("/inv/reports/expiring", { days: 30 });
            const rows = res?.data ?? [];
            if (!rows.length) { this.ref("wrap").innerHTML = `<div class="acc-empty">✅ بچ منقضی‌شونده‌ای در ۳۰ روز آینده وجود ندارد</div>`; return; }
            this._renderTable(rows, true);
        } catch {}
    }

    _renderTable(rows, isExpiring = false) {
        if (!rows.length) { this.ref("wrap").innerHTML = `<div class="acc-empty">بچی یافت نشد</div>`; return; }
        this.ref("wrap").innerHTML = `
        <table class="acc-table">
            <thead><tr>
                <th>شماره بچ</th><th>محصول</th><th>تاریخ تولید</th><th>تاریخ انقضا</th>
                ${isExpiring ? "<th>روز باقیمانده</th>" : ""}
                <th>موجودی</th><th>بهای تمام شده</th><th>اقدام</th>
            </tr></thead>
            <tbody>
            ${rows.map(r => {
                const daysLeft = r.days_left !== undefined ? parseInt(r.days_left) : null;
                const rowStyle = daysLeft !== null && daysLeft <= 7 ? 'style="background:#fef2f2;"' : "";
                return `<tr ${rowStyle}>
                    <td style="font-weight:600;">${this.escape(r.batch_no)}</td>
                    <td>${this.escape(r.product_name ?? "")}</td>
                    <td>${r.mfg_date ?? "—"}</td>
                    <td style="color:${daysLeft !== null && daysLeft <= 30 ? "#ef4444" : "inherit"};">${r.exp_date ?? "—"}</td>
                    ${isExpiring ? `<td style="color:${daysLeft <= 7 ? "#ef4444" : "#f59e0b"};font-weight:700;">${daysLeft} روز</td>` : ""}
                    <td>${this._fmt(r.total_qty)} ${this.escape(r.unit ?? "")}</td>
                    <td>${r.cost_price > 0 ? this._fmt(r.cost_price) + " ﷼" : "—"}</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_qty) > 0 ? "disabled" : ""}>🗑️</button>
                    </td>
                </tr>`;
            }).join("")}
            </tbody>
        </table>`;

        this.ref("wrap").querySelectorAll("[data-edit]").forEach(btn =>
            btn.addEventListener("click", async () => {
                const res = await this.api.get("/inv/batches", { product_id: btn.dataset.pid ?? 0 });
                // find in all batches
                const res2 = await this.api.get("/inv/batches");
                const b = (res2?.data ?? []).find(x => x.id == btn.dataset.edit);
                if (b) this._openModal(b);
            })
        );
        this.ref("wrap").querySelectorAll("[data-del]").forEach(btn =>
            btn.addEventListener("click", async () => {
                if (!confirm("حذف این بچ؟")) return;
                try {
                    await this.api.delete(`/inv/batches/${btn.dataset.del}`);
                    this._toast("✅ حذف شد"); this._load();
                } catch(e) { alert("خطا: " + (e?.message ?? "")); }
            })
        );
    }

    _openModal(b = null) {
        const isEdit = !!b;
        const prodOpts = this._products.map(p =>
            `<option value="${p.id}" ${b?.product_id == p.id ? "selected" : ""}>${this.escape(p.name)}</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="acc-form-group"><label>محصول *</label>
                    <select name="product_id" required><option value="">انتخاب...</option>${prodOpts}</select>
                </div>
                <div class="acc-form-group"><label>شماره بچ / لات *</label>
                    <input name="batch_no" required value="${this.escape(b?.batch_no ?? "")}">
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>تاریخ تولید</label>
                        <input name="mfg_date" type="date" value="${b?.mfg_date ?? ""}">
                    </div>
                    <div class="acc-form-group"><label>تاریخ انقضا</label>
                        <input name="exp_date" type="date" value="${b?.exp_date ?? ""}">
                    </div>
                </div>
                <div class="acc-form-group"><label>بهای تمام شده (ریال)</label>
                    <input name="cost_price" type="number" min="0" step="any" value="${b?.cost_price ?? 0}">
                </div>
                <div class="acc-form-group"><label>یادداشت</label>
                    <input name="notes" value="${this.escape(b?.notes ?? "")}">
                </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.mfg_date) body.mfg_date = null;
            if (!body.exp_date) body.exp_date = null;
            const btn = ev.target.querySelector("[type=submit]");
            btn.disabled = true;
            try {
                if (isEdit) await this.api.put(`/inv/batches/${b.id}`, body);
                else        await this.api.post("/inv/batches", 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);
    }
}
