/**
 * StockSection.js — موجودی فعلی انبار
 */
import SectionBase from "../../accounting/SectionBase.js";

export default class StockSection 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;">
                    <input type="text" data-ref="search" placeholder="جستجو محصول..."
                           class="acc-input" style="width:200px;">
                    <select data-ref="whFilter" class="acc-input">
                        <option value="">همه انبارها</option>
                    </select>
                    <button class="acc-btn acc-btn--warning" data-ref="lowBtn">
                        ⚠️ کم‌موجودی
                    </button>
                    <button class="acc-btn acc-btn--secondary" data-ref="refreshBtn">🔄</button>
                </div>
            </div>

            <!-- آمار سریع -->
            <div class="inv-stats-row" data-ref="statsRow" style="display:flex;gap:12px;margin:12px 0;flex-wrap:wrap;"></div>

            <div data-ref="tableWrap">
                <div class="acc-loading">⏳ در حال بارگذاری...</div>
            </div>
        </div>`;
    }

    async afterRender() {
        await this._loadWarehouses();
        await this._load();

        this.on(this.ref("refreshBtn"), "click", () => this._load());
        this.on(this.ref("lowBtn"),     "click", () => this._loadLow());
        this.on(this.ref("search"),     "input", () => this._filter());
        this.on(this.ref("whFilter"),   "change", () => this._load());
    }

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

    async _load() {
        const whId = this.ref("whFilter")?.value;
        this.ref("tableWrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            let url = whId ? `/inv/stock/warehouse/${whId}` : "/inv/stock";
            const res = await this.api.get(url);
            this._rows = res?.data ?? [];
            this._renderStats();
            this._renderTable(this._rows);
        } catch(e) {
            this.ref("tableWrap").innerHTML = `<div class="acc-error">❌ خطا در بارگذاری</div>`;
        }
    }

    async _loadLow() {
        this.ref("tableWrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری کم‌موجودی‌ها...</div>`;
        try {
            const res = await this.api.get("/inv/stock/low");
            const rows = res?.data ?? [];
            if (!rows.length) {
                this.ref("tableWrap").innerHTML = `<div class="acc-empty">✅ همه محصولات موجودی کافی دارند</div>`;
                return;
            }
            this._renderTable(rows, true);
        } catch {}
    }

    _renderStats() {
        const rows  = this._rows ?? [];
        const total = rows.reduce((s, r) => s + parseFloat(r.stock_value ?? r.qty * (r.avg_cost ?? 0)), 0);
        const items = rows.length;
        const whs   = new Set(rows.map(r => r.warehouse_id)).size;
        this.ref("statsRow").innerHTML = `
            <div class="inv-stat-card">📦 <b>${items}</b> قلم</div>
            <div class="inv-stat-card">🏭 <b>${whs}</b> انبار</div>
            <div class="inv-stat-card">💰 ارزش: <b>${this._fmt(total)}</b> ﷼</div>
        `;
    }

    _renderTable(rows, isLow = false) {
        if (!rows.length) {
            this.ref("tableWrap").innerHTML = `<div class="acc-empty">موجودی یافت نشد</div>`;
            return;
        }
        const html = `
        <table class="acc-table">
            <thead><tr>
                <th>کد</th><th>نام محصول</th><th>انبار</th>
                <th>موجودی</th><th>واحد</th><th>بهای میانگین</th><th>ارزش کل</th>
                ${isLow ? '<th>حداقل</th>' : ''}
            </tr></thead>
            <tbody>
            ${rows.map(r => {
                const qty   = parseFloat(r.qty ?? r.total_qty ?? 0);
                const cost  = parseFloat(r.avg_cost ?? 0);
                const value = qty * cost;
                const low   = isLow && qty <= parseFloat(r.min_stock ?? 0);
                return `<tr ${low ? 'style="background:#fef2f2;"' : ''}>
                    <td>${this.escape(r.product_code ?? r.code ?? '')}</td>
                    <td>${this.escape(r.product_name ?? r.name ?? '')}</td>
                    <td>${this.escape(r.warehouse_name ?? '')}</td>
                    <td style="font-weight:700;color:${qty <= 0 ? '#ef4444' : '#1d4ed8'};">${this._fmt(qty)}</td>
                    <td>${this.escape(r.unit ?? '')}</td>
                    <td>${cost > 0 ? this._fmt(cost) : '—'}</td>
                    <td>${value > 0 ? this._fmt(value) : '—'}</td>
                    ${isLow ? `<td style="color:#ef4444;">${this._fmt(r.min_stock)}</td>` : ''}
                </tr>`;
            }).join("")}
            </tbody>
        </table>`;
        this.ref("tableWrap").innerHTML = html;
    }

    _filter() {
        const q = (this.ref("search")?.value ?? "").toLowerCase();
        if (!q) { this._renderTable(this._rows ?? []); return; }
        const filtered = (this._rows ?? []).filter(r =>
            (r.product_name ?? "").toLowerCase().includes(q) ||
            (r.product_code ?? "").toLowerCase().includes(q)
        );
        this._renderTable(filtered);
    }

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