/**
 * WfStatusSection.js — وضعیت Workflow همه پروژه‌ها
 */
import SectionBase from "../../accounting/SectionBase.js";

export default class WfStatusSection extends SectionBase {

    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="grid" class="wf-status-grid"></div>
        </div>`;
    }

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

    async _load() {
        const grid = this.ref("grid");
        grid.innerHTML = this._skeletons(6);
        try {
            const [projRes, ] = await Promise.all([
                this.api.get("pc/projects"),
                this.api.get("wf/templates"),
            ]);
            const projects = projRes?.data ?? projRes ?? [];
            const instances = await Promise.all(
                projects.map(p => this.api.get(`wf/instances/project/${p.id}`).catch(() => ({ data: null })))
            );
            grid.innerHTML = projects.length
                ? projects.map((p, i) => this._card(p, instances[i]?.data)).join("")
                : `<div class="acc-empty">پروژه‌ای وجود ندارد</div>`;
            this._bindCards(grid, projects, instances);
        } catch (e) {
            grid.innerHTML = `<div class="acc-error">❌ ${this.escape(e.message)}</div>`;
        }
    }

    _card(project, instance) {
        const name = this.escape(project.name || project.title || `#${project.id}`);
        if (!instance) return `
        <div class="wf-project-card wf-card--no-wf">
            <div class="wf-card-title">${name}</div>
            <div class="wf-card-subtitle">${this.escape(project.code || '')}</div>
            <div class="wf-no-workflow">بدون Workflow</div>
        </div>`;

        const stages   = instance.stages ?? [];
        const current  = stages.find(s => s.id == instance.current_stage_id) || stages[0];
        const progress = parseFloat(instance.progress_pct ?? 0);

        const stagesHtml = stages.map(s => {
            const cls = s.status === "completed" ? "wf-stage--done"
                      : s.status === "active"    ? "wf-stage--active"
                      : "wf-stage--pending";
            return `<div class="wf-stage-pill ${cls}">${this.escape(s.icon || '●')} ${this.escape(s.name)}</div>`;
        }).join("");

        const tasks = (current?.tasks ?? []).map(t => {
            const done = t.status === "completed";
            return `
            <div class="wf-task-row ${done ? 'wf-task--done' : ''}">
                <span>${done ? '✅' : (t.is_required ? '🔴' : '⬜')}</span>
                <span class="wf-task-title">${this.escape(t.title)}</span>
                ${!done ? `<button class="acc-btn acc-btn--xs acc-btn--primary" data-complete-task="${t.id}">تکمیل</button>` : ''}
            </div>`;
        }).join("") || `<div style="color:#94a3b8;font-size:12px;">وظیفه‌ای تعریف نشده</div>`;

        return `
        <div class="wf-project-card" data-instance-id="${instance.id}">
            <div class="wf-card-header">
                <div>
                    <div class="wf-card-title">${name}</div>
                    <div class="wf-card-subtitle">${this.escape(project.code || '')} — ${this.escape(instance.template_name || '')}</div>
                </div>
                <button class="acc-btn acc-btn--xs" data-history="${instance.id}" title="تاریخچه">📜</button>
            </div>
            <div class="wf-progress-bar"><div class="wf-progress-fill" style="width:${progress}%"></div></div>
            <div class="wf-progress-label">${progress}% پیشرفت کل</div>
            <div class="wf-stages-strip">${stagesHtml}</div>
            ${current ? `
            <div class="wf-current-stage">
                <div class="wf-stage-name">
                    <span>${current.icon || '📌'}</span>
                    <strong>مرحله جاری: ${this.escape(current.name)}</strong>
                    <span class="wf-stage-progress">${current.progress_pct ?? 0}%</span>
                </div>
                <div class="wf-tasks-list">${tasks}</div>
                ${current.status === "active" ? `
                <div style="text-align:left;margin-top:8px;">
                    <button class="acc-btn acc-btn--primary acc-btn--sm" data-advance="${current.id}">⏭ مرحله بعد</button>
                </div>` : ''}
            </div>` : ''}
        </div>`;
    }

    _bindCards(grid, projects, instances) {
        grid.querySelectorAll("[data-advance]").forEach(btn => {
            btn.addEventListener("click", () => this._advance(btn.dataset.advance));
        });
        grid.querySelectorAll("[data-complete-task]").forEach(btn => {
            btn.addEventListener("click", () => this._completeTask(btn.dataset.completeTask));
        });
        grid.querySelectorAll("[data-history]").forEach(btn => {
            btn.addEventListener("click", () => this._showHistory(btn.dataset.history));
        });
    }

    async _advance(stageId) {
        try {
            const res = await this.api.post(`wf/stages/${stageId}/advance`, {});
            this._toast(res.completed ? "🎉 Workflow تکمیل شد!" : "✅ مرحله بعدی شروع شد");
            await this._load();
        } catch (e) {
            if (e.message.includes("اجباری")) {
                if (confirm(`${e.message}\nبا force ادامه دهید؟`)) {
                    await this.api.post(`wf/stages/${stageId}/advance`, { force: true });
                    await this._load();
                }
            } else alert(e.message);
        }
    }

    async _completeTask(taskId) {
        try {
            await this.api.post(`wf/tasks/${taskId}/complete`, {});
            this._toast("✅ وظیفه تکمیل شد");
            await this._load();
        } catch (e) { alert(e.message); }
    }

    async _showHistory(instanceId) {
        try {
            const res = await this.api.get(`wf/instances/${instanceId}/transitions`);
            const rows = res?.data ?? [];
            const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
            ov.innerHTML = `
            <div class="acc-modal" style="max-width:600px;max-height:80vh;overflow-y:auto;">
                <button class="acc-modal__close">✕</button>
                <div class="acc-modal__title">📜 تاریخچه Workflow</div>
                ${rows.length ? rows.map(t => `
                <div style="border-right:3px solid #3b82f6;padding:10px 12px;margin-bottom:8px;background:#f8fafc;border-radius:6px;">
                    <div style="font-weight:700;font-size:13px;">${this._actionIcon(t.action)} ${this.escape(t.notes)}</div>
                    <div style="font-size:11px;color:#64748b;margin-top:4px;">
                        ${t.from_stage_name ? `از: ${this.escape(t.from_stage_name)} ← ` : ''}
                        ${t.to_stage_name   ? `به: ${this.escape(t.to_stage_name)}` : ''}
                    </div>
                    <div style="font-size:11px;color:#94a3b8;margin-top:3px;">👤 ${this.escape(t.actor_name || 'سیستم')} — ${t.created_at}</div>
                </div>`).join("") : '<div class="acc-empty">تاریخچه‌ای نیست</div>'}
                <div class="acc-modal__actions">
                    <button class="acc-btn acc-btn--secondary" data-action="close">بستن</button>
                </div>
            </div>`;
            document.body.appendChild(ov);
            const close = () => ov.remove();
            ov.querySelector(".acc-modal__close").addEventListener("click", close);
            ov.querySelector("[data-action=close]").addEventListener("click", close);
            ov.addEventListener("click", e => { if (e.target === ov) close(); });
        } catch {}
    }

    _actionIcon(a) { return { create:'🚀', start_stage:'▶️', advance:'⏭️', complete:'🎉' }[a] ?? '🔄'; }

    _skeletons(n = 6) {
        return Array.from({ length: n }, () => `
        <div class="wf-project-card" style="animation:sk-shine 1.4s infinite;">
            <div style="height:16px;background:#e2e8f0;border-radius:4px;width:60%;margin-bottom:10px;"></div>
            <div style="height:8px;background:#e2e8f0;border-radius:4px;margin-bottom:8px;"></div>
            <div style="height:8px;background:#e2e8f0;border-radius:4px;width:80%;"></div>
        </div>`).join("");
    }

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