/**
 * WfAssignSection.js — تخصیص Workflow به پروژه‌ها
 */
import SectionBase from "../../accounting/SectionBase.js";

export default class WfAssignSection extends SectionBase {

    _projects  = [];
    _templates = [];

    async template() {
        return `
        <div class="acc-section-wrap" dir="rtl">
            <div class="acc-toolbar">
                <h2 class="acc-section-title">📁 تخصیص Workflow به پروژه‌ها</h2>
                <button class="acc-btn acc-btn--secondary" data-ref="refreshBtn">🔄 بروزرسانی</button>
            </div>
            <div data-ref="wrap"><div class="acc-loading">⏳ بارگذاری...</div></div>
        </div>`;
    }

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

    async _load() {
        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const [projRes, tplRes] = await Promise.all([
                this.api.get("pc/projects"),
                this.api.get("wf/templates"),
            ]);
            this._projects  = projRes?.data ?? projRes ?? [];
            this._templates = tplRes?.data ?? [];

            const instances = await Promise.all(
                this._projects.map(p => this.api.get(`wf/instances/project/${p.id}`).catch(() => ({ data: null })))
            );
            this._render(instances);
        } catch (e) {
            this.ref("wrap").innerHTML = `<div class="acc-error">❌ ${this.escape(e.message)}</div>`;
        }
    }

    _render(instances) {
        if (!this._projects.length) {
            this.ref("wrap").innerHTML = `<div class="acc-empty">پروژه‌ای وجود ندارد</div>`;
            return;
        }
        const tplOptions = this._templates.map(t =>
            `<option value="${t.id}">${this.escape(t.icon || '')} ${this.escape(t.name)}</option>`
        ).join("");

        const rows = this._projects.map((p, i) => {
            const inst = instances[i]?.data;
            const statusCell = inst
                ? `<span style="background:#d1fae5;color:#065f46;padding:3px 10px;border-radius:10px;font-size:12px;font-weight:600;">✅ ${this.escape(inst.template_name || 'دارد')}</span>`
                : `<span style="background:#f1f5f9;color:#94a3b8;padding:3px 10px;border-radius:10px;font-size:12px;">بدون Workflow</span>`;
            const actionCell = inst
                ? `<button class="acc-btn acc-btn--xs acc-btn--danger" data-remove="${inst.id}">🗑 حذف</button>`
                : `<div style="display:flex;gap:6px;align-items:center;">
                    <select class="acc-select" data-proj="${p.id}">${tplOptions}</select>
                    <button class="acc-btn acc-btn--xs acc-btn--primary" data-assign="${p.id}">✅ تخصیص</button>
                   </div>`;
            return `
            <tr>
                <td>${this.escape(p.name || p.title || `#${p.id}`)}</td>
                <td>${this.escape(p.code || '-')}</td>
                <td>${statusCell}</td>
                <td>${actionCell}</td>
            </tr>`;
        }).join("");

        this.ref("wrap").innerHTML = `
        <div style="overflow-x:auto;">
            <table class="acc-table">
                <thead><tr><th>نام پروژه</th><th>کد</th><th>وضعیت Workflow</th><th>عملیات</th></tr></thead>
                <tbody>${rows}</tbody>
            </table>
        </div>`;

        this.ref("wrap").querySelectorAll("[data-assign]").forEach(btn => {
            btn.addEventListener("click", async () => {
                const pid = btn.dataset.assign;
                const sel = this.ref("wrap").querySelector(`select[data-proj="${pid}"]`);
                if (!sel?.value) return;
                try {
                    await this.api.post("wf/instances", { project_id: +pid, template_id: +sel.value });
                    this._toast("✅ Workflow تخصیص یافت");
                    await this._load();
                } catch (e) { alert(e.message); }
            });
        });

        this.ref("wrap").querySelectorAll("[data-remove]").forEach(btn => {
            btn.addEventListener("click", async () => {
                if (!confirm("Workflow این پروژه حذف شود؟")) return;
                try {
                    await this.api.delete(`wf/instances/${btn.dataset.remove}`);
                    this._toast("✅ Workflow حذف شد");
                    await this._load();
                } catch (e) { alert(e.message); }
            });
        });
    }

    _toast(msg) {
        const t = document.createElement("div");
        t.style.cssText = "position:fixed;bottom:24px;left:24px;background:#10b981;color:#fff;padding:12px 20px;border-radius:10px;font-size:13px;z-index:9999;";
        t.textContent = msg; document.body.appendChild(t); setTimeout(() => t.remove(), 3000);
    }

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