/**
 * AssetCategoriesSection.js — دسته‌بندی + استهلاک
 */
import SectionBase from "../../accounting/SectionBase.js";

export default class AssetCategoriesSection 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("/assets/categories");
            this._rows = res?.data ?? [];
            this._render();
        } catch { this.ref("wrap").innerHTML = `<div class="acc-error">❌ خطا</div>`; }
    }

    _render() {
        if (!this._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></tr></thead>
            <tbody>
            ${this._rows.map(c => `<tr>
                <td><small style="font-family:monospace;">${this.escape(c.code)}</small></td>
                <td><b>${c.icon} ${this.escape(c.name)}</b></td>
                <td><b style="color:#3b82f6;">${c.useful_years}</b> سال</td>
                <td>${c.salvage_pct}٪</td>
                <td><span style="background:#dbeafe;color:#1e40af;padding:2px 8px;border-radius:10px;font-size:11px;font-weight:700;">${c.asset_count}</span></td>
                <td><button class="acc-btn acc-btn--xs" data-edit="${c.id}">✏️</button></td>
            </tr>`).join("")}
            </tbody>
        </table>`;

        this.ref("wrap").querySelectorAll("[data-edit]").forEach(b =>
            b.addEventListener("click", () => this._openModal(this._rows.find(r => r.id == b.dataset.edit)))
        );
    }

    _openModal(c = null) {
        const isEdit = !!c;
        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:440px;">
            <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" value="${this.escape(c?.code ?? '')}"></div>
                    <div class="acc-form-group"><label>نام *</label><input name="name" required value="${this.escape(c?.name ?? '')}"></div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>آیکن</label><input name="icon" value="${this.escape(c?.icon ?? '📦')}"></div>
                    <div class="acc-form-group"><label>روش استهلاک</label>
                        <select name="depr_method">
                            <option value="straight_line" ${c?.depr_method === 'straight_line' ? 'selected' : ''}>خط مستقیم</option>
                            <option value="declining" ${c?.depr_method === 'declining' ? 'selected' : ''}>کاهنده</option>
                            <option value="none" ${c?.depr_method === 'none' ? 'selected' : ''}>بدون استهلاک</option>
                        </select>
                    </div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>عمر مفید (سال)</label>
                        <input name="useful_years" type="number" min="1" max="100" value="${c?.useful_years ?? 5}">
                    </div>
                    <div class="acc-form-group"><label>ارزش اسقاط (٪)</label>
                        <input name="salvage_pct" type="number" min="0" max="100" step="0.1" value="${c?.salvage_pct ?? 0}">
                    </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());
            try {
                if (isEdit) await this.api.put(`/assets/categories/${c.id}`, body);
                else        await this.api.post("/assets/categories", body);
                close(); this._load();
            } catch(e) { alert("خطا: " + (e?.message ?? "")); }
        });
    }

    escape(s) { return String(s ?? "").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"); }
}
