/**
 * WfTemplatesSection.js — مدیریت قالب‌های Workflow
 */
import SectionBase from "../../accounting/SectionBase.js";

export default class WfTemplatesSection extends SectionBase {

    _templates = [];
    _selected  = null;

    async template() {
        return `
        <div class="acc-section-wrap" dir="rtl">
            <div class="acc-toolbar">
                <h2 class="acc-section-title">⚙️ قالب‌های Workflow</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 style="display:grid;grid-template-columns:240px 1fr;gap:16px;min-height:500px;">
                <div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:10px;overflow:hidden;">
                    <div style="padding:12px;font-weight:700;font-size:13px;color:#475569;background:#f1f5f9;border-bottom:1px solid #e2e8f0;">قالب‌های موجود</div>
                    <ul data-ref="tplList" style="list-style:none;padding:0;margin:0;"></ul>
                </div>
                <div data-ref="detail" style="background:#fff;border:1px solid #e2e8f0;border-radius:10px;padding:16px;">
                    <div class="acc-empty">یک قالب را انتخاب کنید یا قالب جدید بسازید.</div>
                </div>
            </div>
        </div>`;
    }

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

    async _load() {
        try {
            const res = await this.api.get("wf/templates");
            this._templates = res?.data ?? [];
            this._renderList();
        } catch (e) {
            this.ref("tplList").innerHTML = `<li style="padding:12px;color:#dc2626;font-size:12px;">خطا: ${this.escape(e.message)}</li>`;
        }
    }

    _renderList() {
        const list = this.ref("tplList");
        if (!this._templates.length) {
            list.innerHTML = `<li style="padding:12px 16px;color:#94a3b8;font-size:13px;">قالبی وجود ندارد</li>`;
            return;
        }
        list.innerHTML = this._templates.map(t => `
        <li data-tpl-id="${t.id}" style="display:flex;justify-content:space-between;align-items:center;
             padding:10px 12px;cursor:pointer;font-size:13px;color:#334155;
             border-bottom:1px solid #f1f5f9;transition:background .1s;"
            onmouseenter="this.style.background='#eff6ff'" onmouseleave="this.style.background=''">
            <span>${this.escape(t.icon || '📋')} ${this.escape(t.name)}</span>
            <span style="font-size:11px;color:#94a3b8;">${t.stage_count ?? 0} مرحله</span>
        </li>`).join("");

        list.querySelectorAll("li[data-tpl-id]").forEach(li => {
            li.addEventListener("click", async () => {
                list.querySelectorAll("li").forEach(i => i.style.background = "");
                li.style.background = "#dbeafe";
                li.style.color = "#1d4ed8";
                await this._loadDetail(li.dataset.tplId);
            });
        });
    }

    async _loadDetail(tplId) {
        const detail = this.ref("detail");
        detail.innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res = await this.api.get(`wf/templates/${tplId}`);
            const tpl = res?.data;
            if (!tpl) { detail.innerHTML = `<div class="acc-empty">یافت نشد</div>`; return; }
            this._selected = tpl;
            this._renderDetail(tpl);
        } catch (e) { detail.innerHTML = `<div class="acc-error">❌ ${this.escape(e.message)}</div>`; }
    }

    _renderDetail(tpl) {
        const detail = this.ref("detail");
        const stagesHtml = (tpl.stages ?? []).map((s, si) => `
        <div style="border:1px solid #e2e8f0;border-radius:8px;overflow:hidden;margin-bottom:10px;">
            <div style="background:#f1f5f9;padding:10px 14px;display:flex;justify-content:space-between;align-items:center;">
                <span style="font-weight:700;font-size:13px;">${this.escape(s.icon || '▶')} ${si+1}. ${this.escape(s.name)}</span>
                <span style="font-size:11px;color:#94a3b8;">ترتیب: ${s.sort_order} | بودجه: ${s.budget_pct}%</span>
            </div>
            <div style="padding:10px 14px;">
                ${(s.tasks ?? []).map(t => `
                <div style="font-size:12px;color:#475569;padding:3px 0;">
                    ${t.is_required ? '🔴' : '⬜'} ${this.escape(t.title)}
                </div>`).join("") || `<div style="color:#94a3b8;font-size:12px;">وظیفه‌ای تعریف نشده</div>`}
            </div>
        </div>`).join("") || `<div class="acc-empty">مرحله‌ای تعریف نشده</div>`;

        detail.innerHTML = `
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px;flex-wrap:wrap;gap:8px;">
            <div>
                <span style="font-size:26px;">${tpl.icon || '📋'}</span>
                <strong style="font-size:16px;margin-right:8px;">${this.escape(tpl.name)}</strong>
                <span style="background:#f1f5f9;color:#64748b;padding:2px 8px;border-radius:10px;font-size:11px;">${tpl.instance_count ?? 0} پروژه</span>
            </div>
            <div style="display:flex;gap:6px;">
                <button class="acc-btn acc-btn--sm" data-ref="editBtn">✏️ ویرایش</button>
                ${!tpl.is_system ? `<button class="acc-btn acc-btn--sm acc-btn--danger" data-ref="delBtn">🗑 حذف</button>` : ''}
                <button class="acc-btn acc-btn--sm acc-btn--primary" data-ref="addStageBtn">+ مرحله</button>
            </div>
        </div>
        ${tpl.description ? `<p style="font-size:13px;color:#64748b;margin-bottom:14px;">${this.escape(tpl.description)}</p>` : ''}
        <div data-ref="stagesWrap">${stagesHtml}</div>
        <div data-ref="stageFormArea"></div>`;

        this._bindRefs();

        this.ref("editBtn")?.addEventListener("click", () => this._renderForm(tpl));
        this.ref("delBtn")?.addEventListener("click", () => this._delete(tpl));
        this.ref("addStageBtn")?.addEventListener("click", () => this._renderStageForm(tpl.id));
    }

    async _delete(tpl) {
        if (!confirm(`قالب «${tpl.name}» حذف شود؟`)) return;
        try {
            await this.api.delete(`wf/templates/${tpl.id}`);
            this.ref("detail").innerHTML = `<div class="acc-empty">قالب حذف شد.</div>`;
            await this._load();
        } catch (e) { alert(e.message); }
    }

    _renderForm(tpl) {
        const isEdit = !!tpl;
        const detail = this.ref("detail");
        detail.innerHTML = `
        <h3 style="margin:0 0 16px;font-size:15px;">${isEdit ? "✏️ ویرایش قالب" : "➕ قالب جدید"}</h3>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:14px;">
            <label style="display:flex;flex-direction:column;gap:5px;font-size:13px;color:#475569;">نام قالب *
                <input class="acc-input" data-ref="fname" value="${this.escape(tpl?.name || '')}" placeholder="مثلاً: پروژه ساختمانی">
            </label>
            <label style="display:flex;flex-direction:column;gap:5px;font-size:13px;color:#475569;">کد (code)
                <input class="acc-input" data-ref="fcode" value="${this.escape(tpl?.code || '')}" placeholder="construction" ${isEdit ? 'disabled' : ''}>
            </label>
            <label style="display:flex;flex-direction:column;gap:5px;font-size:13px;color:#475569;">آیکون
                <input class="acc-input" data-ref="ficon" value="${this.escape(tpl?.icon || '📋')}" maxlength="4">
            </label>
            <label style="display:flex;flex-direction:column;gap:5px;font-size:13px;color:#475569;">رنگ
                <input type="color" class="acc-input" data-ref="fcolor" value="${tpl?.color || '#3b82f6'}" style="height:36px;padding:3px;">
            </label>
            <label style="display:flex;flex-direction:column;gap:5px;font-size:13px;color:#475569;grid-column:1/-1;">توضیحات
                <textarea class="acc-input" data-ref="fdesc" rows="2">${this.escape(tpl?.description || '')}</textarea>
            </label>
        </div>
        <div style="display:flex;gap:8px;">
            <button class="acc-btn acc-btn--primary" data-ref="saveBtn">💾 ذخیره</button>
            <button class="acc-btn acc-btn--secondary" data-ref="cancelBtn">لغو</button>
        </div>`;

        this._bindRefs();

        this.ref("cancelBtn").addEventListener("click", async () => {
            if (isEdit) this._renderDetail(tpl);
            else detail.innerHTML = `<div class="acc-empty">یک قالب را انتخاب کنید یا قالب جدید بسازید.</div>`;
        });

        this.ref("saveBtn").addEventListener("click", async () => {
            const name = this.ref("fname").value.trim();
            if (!name) { alert("نام الزامی است"); return; }
            const payload = {
                name,
                description: this.ref("fdesc").value,
                icon:  this.ref("ficon").value,
                color: this.ref("fcolor").value,
            };
            if (!isEdit) payload.code = this.ref("fcode").value.trim();
            try {
                if (isEdit) await this.api.put(`wf/templates/${tpl.id}`, payload);
                else        await this.api.post("wf/templates", payload);
                await this._load();
                if (isEdit) await this._loadDetail(tpl.id);
                else detail.innerHTML = `<div class="acc-empty">قالب ذخیره شد. از لیست انتخاب کنید.</div>`;
            } catch (e) { alert(e.message); }
        });
    }

    _renderStageForm(tplId) {
        const area = this.ref("stageFormArea");
        if (!area) return;
        let tasks = [];

        area.innerHTML = `
        <div style="border:1px solid #3b82f6;border-radius:10px;padding:16px;margin-top:14px;">
            <h4 style="margin:0 0 14px;font-size:14px;color:#1d4ed8;">➕ مرحله جدید</h4>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:12px;">
                <label style="display:flex;flex-direction:column;gap:4px;font-size:12px;">نام *
                    <input class="acc-input" data-ref="sname" placeholder="مثلاً: طراحی">
                </label>
                <label style="display:flex;flex-direction:column;gap:4px;font-size:12px;">کد
                    <input class="acc-input" data-ref="scode" placeholder="design">
                </label>
                <label style="display:flex;flex-direction:column;gap:4px;font-size:12px;">آیکون
                    <input class="acc-input" data-ref="sicon" value="▶" maxlength="4">
                </label>
                <label style="display:flex;flex-direction:column;gap:4px;font-size:12px;">ترتیب
                    <input type="number" class="acc-input" data-ref="sorder" value="10">
                </label>
                <label style="display:flex;flex-direction:column;gap:4px;font-size:12px;">% بودجه
                    <input type="number" class="acc-input" data-ref="sbudget" value="0" min="0" max="100">
                </label>
            </div>
            <div style="background:#fff;border:1px solid #e2e8f0;border-radius:8px;padding:12px;margin-bottom:12px;">
                <div style="font-weight:600;font-size:12px;margin-bottom:8px;">وظایف مرحله:</div>
                <div data-ref="tasksArea"></div>
                <button class="acc-btn acc-btn--xs" data-ref="addTaskBtn">+ وظیفه</button>
            </div>
            <div style="display:flex;gap:8px;">
                <button class="acc-btn acc-btn--primary acc-btn--sm" data-ref="saveStageBtn">💾 ذخیره</button>
                <button class="acc-btn acc-btn--secondary acc-btn--sm" data-ref="cancelStageBtn">لغو</button>
            </div>
        </div>`;

        this._bindRefs();

        const renderTasks = () => {
            const ta = this.ref("tasksArea");
            ta.innerHTML = tasks.map((t, i) => `
            <div style="display:flex;gap:6px;align-items:center;margin-bottom:6px;">
                <input class="acc-input" style="flex:1;" data-ti="${i}" value="${this.escape(t.title)}" placeholder="عنوان وظیفه">
                <label style="font-size:11px;display:flex;align-items:center;gap:3px;white-space:nowrap;">
                    <input type="checkbox" data-ri="${i}" ${t.is_required ? 'checked' : ''}> اجباری
                </label>
                <button class="acc-btn acc-btn--xs acc-btn--danger" data-di="${i}">✕</button>
            </div>`).join("");
            ta.querySelectorAll("[data-ti]").forEach(inp => inp.addEventListener("input",  () => { tasks[inp.dataset.ti].title = inp.value; }));
            ta.querySelectorAll("[data-ri]").forEach(chk => chk.addEventListener("change", () => { tasks[chk.dataset.ri].is_required = chk.checked; }));
            ta.querySelectorAll("[data-di]").forEach(btn => btn.addEventListener("click",  () => { tasks.splice(+btn.dataset.di, 1); renderTasks(); }));
        };
        renderTasks();

        this.ref("addTaskBtn").addEventListener("click", () => { tasks.push({ title: "", is_required: false }); renderTasks(); });
        this.ref("cancelStageBtn").addEventListener("click", () => { area.innerHTML = ""; });

        this.ref("saveStageBtn").addEventListener("click", async () => {
            const name = this.ref("sname").value.trim();
            if (!name) { alert("نام مرحله الزامی است"); return; }
            try {
                await this.api.post(`wf/templates/${tplId}/stages`, {
                    name, code: this.ref("scode").value.trim(),
                    icon: this.ref("sicon").value,
                    sort_order: +this.ref("sorder").value,
                    budget_pct: +this.ref("sbudget").value || 0,
                    tasks: tasks.filter(t => t.title.trim()),
                });
                area.innerHTML = "";
                await this._loadDetail(tplId);
            } catch (e) { alert(e.message); }
        });
    }

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