/**
 * SerialsSection.js — ردیابی سریال نامبر
 */
import SectionBase from "../../accounting/SectionBase.js";

const SERIAL_STATUS = {
    in_stock:  { label: "در انبار",    color: "#10b981" },
    issued:    { label: "صادر شده",    color: "#3b82f6" },
    returned:  { label: "مرجوع شده",   color: "#8b5cf6" },
    scrapped:  { label: "اسقاط",       color: "#ef4444" },
    lost:      { label: "مفقود",        color: "#f59e0b" },
};

export default class SerialsSection 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;align-items:center;flex-wrap:wrap;">
                    <input type="text" data-ref="search" placeholder="جستجو سریال..."
                           class="acc-input" style="width:200px;">
                    <select data-ref="statusFilter" class="acc-input">
                        <option value="">همه وضعیت‌ها</option>
                        ${Object.entries(SERIAL_STATUS).map(([k,v]) =>
                            `<option value="${k}">${v.label}</option>`
                        ).join("")}
                    </select>
                    <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("statusFilter"), "change", () => this._load());
        let timer;
        this.on(this.ref("search"), "input", () => {
            clearTimeout(timer);
            timer = setTimeout(() => this._load(), 400);
        });
    }

    async _load() {
        const params = {};
        const status = this.ref("statusFilter")?.value;
        const search = this.ref("search")?.value?.trim();
        if (status) params.status = status;
        if (search) params.search = search;

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

    _renderTable(rows) {
        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><th>بچ</th><th>صادر به</th><th>اقدام</th>
            </tr></thead>
            <tbody>
            ${rows.map(r => {
                const s = SERIAL_STATUS[r.status] ?? { label: r.status, color: "#64748b" };
                return `<tr>
                    <td style="font-weight:700;font-family:monospace;">${this.escape(r.serial_no)}</td>
                    <td>${this.escape(r.product_name ?? "")} <small style="color:#94a3b8;">${this.escape(r.product_code ?? "")}</small></td>
                    <td><span style="color:${s.color};font-weight:600;">${s.label}</span></td>
                    <td>${this.escape(r.warehouse_name ?? "—")}</td>
                    <td><small>${this.escape(r.batch_no ?? "—")}</small></td>
                    <td><small>${this.escape(r.issued_to ?? "—")}</small></td>
                    <td><button class="acc-btn acc-btn--xs" data-id="${r.id}" data-status="${r.status}">✏️</button></td>
                </tr>`;
            }).join("")}
            </tbody>
        </table>`;

        this.ref("wrap").querySelectorAll("[data-id]").forEach(btn =>
            btn.addEventListener("click", () => {
                const row = rows.find(r => r.id == btn.dataset.id);
                if (row) this._openEditModal(row);
            })
        );
    }

    _openEditModal(serial) {
        const s = SERIAL_STATUS[serial.status] ?? { label: serial.status };
        const statusOpts = Object.entries(SERIAL_STATUS).map(([k,v]) =>
            `<option value="${k}" ${serial.status === k ? "selected" : ""}>${v.label}</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>
            <div style="background:#f8fafc;padding:10px;border-radius:8px;margin-bottom:12px;font-size:13px;">
                <b>${this.escape(serial.serial_no)}</b><br>
                <small>${this.escape(serial.product_name ?? "")}</small>
            </div>
            <form>
                <div class="acc-form-group"><label>وضعیت</label>
                    <select name="status">${statusOpts}</select>
                </div>
                <div class="acc-form-group"><label>صادر به</label>
                    <input name="issued_to" value="${this.escape(serial.issued_to ?? "")}">
                </div>
                <div class="acc-form-group"><label>یادداشت</label>
                    <input name="notes" value="${this.escape(serial.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());
            const btn  = ev.target.querySelector("[type=submit]");
            btn.disabled = true;
            try {
                await this.api.put(`/inv/serials/${serial.id}`, body);
                close(); this._toast("✅ سریال به‌روز شد"); this._load();
            } catch(e) { alert("خطا: " + (e?.message ?? "")); btn.disabled = false; }
        });
    }

    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);
    }
}
