/**
 * WorkflowSection.js — Workflow پروژه (Stepper + Tasks + Gates)
 */
import SectionBase from "../../accounting/SectionBase.js";

const STATUS = {
    pending:   { label: 'در انتظار', color: '#94a3b8', icon: '⏸' },
    active:    { label: 'در حال اجرا',  color: '#3b82f6', icon: '🔄' },
    completed: { label: 'تکمیل شده',     color: '#10b981', icon: '✅' },
    skipped:   { label: 'رد شده',        color: '#f59e0b', icon: '⏭' },
    blocked:   { label: 'مسدود',         color: '#ef4444', icon: '🚫' },
};

export default class WorkflowSection extends SectionBase {

    constructor(p) {
        super(p);
        this._project   = null;
        this._instance  = null;
        this._activeStageId = null;
        this._templates = [];
    }

    async template() {
        return `
        <div class="acc-section-wrap">
            <div class="acc-toolbar">
                <h2 class="acc-section-title">🔄 Workflow پروژه</h2>
                <div style="display:flex;gap:8px;">
                    <button class="acc-btn acc-btn--secondary" data-ref="historyBtn">📜 تاریخچه</button>
                    <button class="acc-btn acc-btn--secondary" data-ref="refreshBtn">🔄</button>
                </div>
            </div>
            <div data-ref="wrap" style="display:flex;flex-direction:column;gap:14px;">
                <div class="acc-loading">⏳ بارگذاری...</div>
            </div>
        </div>`;
    }

    async afterRender() {
        this._project = this.store?.get("context.project") ?? null;
        await this._loadTemplates();
        await this._load();

        this.on(this.ref("refreshBtn"), "click", () => this._load());
        this.on(this.ref("historyBtn"), "click", () => this._showHistory());

        // به تغییر پروژه واکنش نشان بده
        this._unsubscribe = this.store?.subscribe?.("context.project", (p) => {
            this._project = p;
            this._load();
        });
    }

    async _loadTemplates() {
        try { const r = await this.api.get("/wf/templates"); this._templates = r?.data ?? []; } catch {}
    }

    async _load() {
        if (!this._project?.id) {
            this.ref("wrap").innerHTML = `
                <div class="acc-empty" style="padding:40px;text-align:center;">
                    <div style="font-size:48px;margin-bottom:8px;">📊</div>
                    <div>لطفاً یک پروژه را از تب «پروژه‌ها» انتخاب کنید</div>
                </div>`;
            return;
        }

        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری workflow...</div>`;
        try {
            const res = await this.api.get(`/wf/instances/project/${this._project.id}`);
            this._instance = res?.data ?? null;

            if (!this._instance) {
                this._renderTemplatePicker();
            } else {
                if (!this._activeStageId) {
                    const current = this._instance.stages?.find(s => s.status === 'active');
                    this._activeStageId = current?.id ?? this._instance.stages?.[0]?.id;
                }
                this._render();
            }
        } catch {
            this.ref("wrap").innerHTML = `<div class="acc-error">❌ خطا</div>`;
        }
    }

    /* ── انتخاب قالب برای شروع workflow ── */
    _renderTemplatePicker() {
        if (!this._templates.length) {
            this.ref("wrap").innerHTML = `<div class="acc-empty">قالبی تعریف نشده است</div>`;
            return;
        }
        this.ref("wrap").innerHTML = `
        <div style="background:#eff6ff;padding:14px;border-radius:8px;color:#1e40af;font-size:13px;">
            💡 برای این پروژه (<b>${this.escape(this._project.name || `#${this._project.id}`)}</b>) workflowی تعریف نشده است.
            یک قالب انتخاب کنید:
        </div>
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:14px;">
            ${this._templates.map(t => `
            <div style="border:1.5px solid ${t.color};border-radius:10px;padding:14px;background:#fff;cursor:pointer;transition:transform .15s;"
                 class="wf-tpl-card" data-tpl="${t.id}"
                 onmouseenter="this.style.transform='translateY(-2px)';this.style.boxShadow='0 4px 12px rgba(0,0,0,.1)'"
                 onmouseleave="this.style.transform='';this.style.boxShadow=''">
                <div style="font-size:24px;margin-bottom:6px;">${t.icon}</div>
                <div style="font-weight:700;font-size:14px;color:${t.color};">${this.escape(t.name)}</div>
                <div style="font-size:12px;color:#64748b;margin-top:4px;">${this.escape(t.description ?? '')}</div>
                <div style="font-size:11px;color:#94a3b8;margin-top:8px;">
                    📋 ${t.stage_count} مرحله | ✅ ${t.instance_count} پروژه استفاده شده
                </div>
                <button class="acc-btn acc-btn--primary acc-btn--sm" style="margin-top:10px;background:${t.color};border-color:${t.color};">
                    🚀 اعمال این قالب
                </button>
            </div>`).join("")}
        </div>`;

        this.ref("wrap").querySelectorAll(".wf-tpl-card").forEach(card =>
            card.addEventListener("click", () => this._applyTemplate(parseInt(card.dataset.tpl)))
        );
    }

    async _applyTemplate(templateId) {
        const tpl = this._templates.find(t => t.id == templateId);
        if (!confirm(`اعمال قالب «${tpl?.name}» روی این پروژه؟`)) return;
        try {
            await this.api.post("/wf/instances", {
                project_id: this._project.id,
                template_id: templateId,
            });
            this._toast("✅ Workflow ایجاد شد", "#10b981");
            this._load();
        } catch(e) { alert("خطا: " + (e?.message ?? "")); }
    }

    /* ── نمایش instance ── */
    _render() {
        const inst = this._instance;
        const activeStage = inst.stages?.find(s => s.id == this._activeStageId);

        this.ref("wrap").innerHTML = `
        ${this._renderHeader(inst)}
        ${this._renderStepper(inst)}
        ${activeStage ? this._renderStagePanel(activeStage) : ''}
        `;

        // bind clicks روی stages
        this.ref("wrap").querySelectorAll("[data-stage-id]").forEach(el =>
            el.addEventListener("click", () => {
                this._activeStageId = parseInt(el.dataset.stageId);
                this._render();
            })
        );

        // bind taskها
        this.ref("wrap").querySelectorAll("[data-task]").forEach(chk =>
            chk.addEventListener("change", () => this._toggleTask(parseInt(chk.dataset.task), chk.checked))
        );

        const adv = this.ref("wrap").querySelector("[data-action=advance]");
        if (adv) adv.addEventListener("click", () => this._advance(activeStage));

        const start = this.ref("wrap").querySelector("[data-action=start]");
        if (start) start.addEventListener("click", () => this._startStage(activeStage));

        const edit = this.ref("wrap").querySelector("[data-action=edit-stage]");
        if (edit) edit.addEventListener("click", () => this._editStage(activeStage));
    }

    _renderHeader(inst) {
        const progress = parseFloat(inst.progress_pct ?? 0);
        return `
        <div style="background:linear-gradient(135deg,#eff6ff 0%,#f0fdf4 100%);padding:16px;border-radius:10px;border:1px solid #e2e8f0;">
            <div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px;">
                <div>
                    <div style="font-size:13px;color:#64748b;">قالب workflow:</div>
                    <div style="font-weight:700;font-size:16px;">
                        ${inst.template_icon ?? ''} ${this.escape(inst.template_name ?? '—')}
                    </div>
                </div>
                <div style="text-align:left;">
                    <div style="font-size:12px;color:#64748b;">پیشرفت کل</div>
                    <div style="font-weight:700;font-size:24px;color:#10b981;">${progress}%</div>
                </div>
            </div>
            <div style="height:8px;background:#e2e8f0;border-radius:4px;overflow:hidden;margin-top:10px;">
                <div style="height:100%;background:linear-gradient(90deg,#3b82f6,#10b981);width:${progress}%;transition:width .3s;"></div>
            </div>
        </div>`;
    }

    /** Stepper افقی */
    _renderStepper(inst) {
        return `
        <div style="overflow-x:auto;padding:8px 0;">
            <div style="display:flex;gap:0;align-items:stretch;min-width:100%;">
                ${inst.stages.map((s, idx) => {
                    const st = STATUS[s.status] ?? STATUS.pending;
                    const isActive = s.id == this._activeStageId;
                    return `
                    <div data-stage-id="${s.id}" style="flex:1;min-width:130px;cursor:pointer;display:flex;flex-direction:column;align-items:center;padding:0 4px;">
                        <!-- خط اتصال -->
                        <div style="height:3px;width:100%;background:linear-gradient(90deg,
                            ${idx === 0 ? 'transparent' : (s.status === 'pending' ? '#e2e8f0' : st.color)} 0%,
                            ${idx === 0 ? 'transparent' : (s.status === 'pending' ? '#e2e8f0' : st.color)} 50%,
                            ${idx === inst.stages.length - 1 ? 'transparent' : (s.status === 'pending' ? '#e2e8f0' : st.color)} 100%);
                            margin-top:20px;"></div>

                        <!-- آیکن مرحله -->
                        <div style="background:${isActive ? st.color : (s.status === 'pending' ? '#fff' : st.color+'1a')};
                                    color:${isActive ? '#fff' : st.color};
                                    border:3px solid ${st.color};
                                    width:44px;height:44px;border-radius:50%;
                                    display:flex;align-items:center;justify-content:center;font-size:18px;
                                    margin-top:-25px;
                                    box-shadow:${isActive ? '0 4px 12px '+st.color+'66' : 'none'};
                                    transition:all .2s;">
                            ${s.icon || st.icon}
                        </div>

                        <!-- نام -->
                        <div style="margin-top:6px;text-align:center;">
                            <div style="font-size:12px;font-weight:${isActive ? '700' : '500'};color:${isActive ? st.color : '#475569'};">
                                ${this.escape(s.name)}
                            </div>
                            <div style="font-size:10px;color:#94a3b8;margin-top:2px;">
                                ${s.tasks_done}/${s.tasks_total} ${st.label}
                            </div>
                        </div>
                    </div>`;
                }).join("")}
            </div>
        </div>`;
    }

    /** پانل جزئیات مرحله انتخاب شده */
    _renderStagePanel(stage) {
        const st = STATUS[stage.status] ?? STATUS.pending;
        const canAdvance = stage.status === 'active';
        const canStart   = stage.status === 'pending';

        return `
        <div style="border:1.5px solid ${st.color};border-radius:10px;overflow:hidden;background:#fff;">
            <!-- هدر مرحله -->
            <div style="background:${st.color};color:#fff;padding:12px 16px;display:flex;justify-content:space-between;align-items:center;">
                <div>
                    <div style="font-size:18px;font-weight:700;">${stage.icon} ${this.escape(stage.name)}</div>
                    <div style="font-size:12px;opacity:.9;margin-top:2px;">${st.icon} ${st.label} — ${stage.progress_pct}% تکمیل</div>
                </div>
                <div style="display:flex;gap:6px;">
                    ${canStart ? `<button class="acc-btn acc-btn--sm" data-action="start" style="background:#fff;color:${st.color};">▶️ شروع</button>` : ''}
                    ${canAdvance ? `<button class="acc-btn acc-btn--sm" data-action="advance" style="background:#fff;color:${st.color};font-weight:700;">⏭️ مرحله بعد</button>` : ''}
                    <button class="acc-btn acc-btn--sm" data-action="edit-stage" style="background:rgba(255,255,255,.2);color:#fff;border-color:#fff;">✏️</button>
                </div>
            </div>

            <!-- بدنه: tasks + gates + اطلاعات -->
            <div style="display:grid;grid-template-columns:2fr 1fr;gap:16px;padding:16px;">

                <!-- Tasks -->
                <div>
                    <h4 style="margin:0 0 10px 0;font-size:13px;color:#475569;">📋 Tasks (${stage.tasks_done}/${stage.tasks_total})</h4>
                    ${stage.tasks?.length ? stage.tasks.map(t => {
                        const done = t.status === 'completed';
                        return `
                        <label style="display:flex;gap:8px;align-items:flex-start;padding:8px;border-radius:6px;cursor:pointer;
                                      background:${done ? '#f0fdf4' : '#f8fafc'};margin-bottom:4px;border:1px solid ${done ? '#86efac' : '#e2e8f0'};">
                            <input type="checkbox" data-task="${t.id}" ${done ? 'checked' : ''} style="margin-top:2px;">
                            <div style="flex:1;">
                                <div style="font-size:13px;font-weight:600;${done ? 'text-decoration:line-through;color:#94a3b8;' : 'color:#1e293b;'}">
                                    ${this.escape(t.title)}
                                    ${t.is_required == 1 ? '<small style="color:#ef4444;">*</small>' : ''}
                                </div>
                                ${t.assigned_name ? `<div style="font-size:11px;color:#64748b;margin-top:2px;">👤 ${this.escape(t.assigned_name)}</div>` : ''}
                                ${t.due_date     ? `<div style="font-size:11px;color:#f59e0b;margin-top:2px;">📅 ${t.due_date}</div>` : ''}
                                ${done && t.completed_by_name ? `<div style="font-size:10px;color:#10b981;margin-top:2px;">✅ توسط ${this.escape(t.completed_by_name)}</div>` : ''}
                            </div>
                        </label>`;
                    }).join('') : '<div style="color:#94a3b8;font-size:12px;padding:12px;">taskی تعریف نشده</div>'}
                </div>

                <!-- Gates + اطلاعات -->
                <div>
                    <h4 style="margin:0 0 10px 0;font-size:13px;color:#475569;">🚦 Gates ورود به مرحله بعد</h4>
                    ${stage.gates?.length ? stage.gates.map(g => `
                        <div style="font-size:12px;padding:6px;background:#fef9c3;border-right:3px solid #eab308;margin-bottom:4px;border-radius:4px;">
                            ⚠️ ${this.escape(g.title)}
                        </div>
                    `).join('') : '<div style="color:#94a3b8;font-size:12px;">بدون gate</div>'}

                    <h4 style="margin:14px 0 10px 0;font-size:13px;color:#475569;">💰 بودجه</h4>
                    <div style="background:#eff6ff;padding:10px;border-radius:6px;font-size:12px;">
                        <div>اختصاص: <b>${this._fmt(stage.budget_amount)} ﷼</b></div>
                        <div style="color:#dc2626;margin-top:4px;">مصرف: <b>${this._fmt(stage.spent_amount)} ﷼</b></div>
                        ${stage.budget_amount > 0 ? `
                        <div style="margin-top:6px;height:6px;background:#fff;border-radius:3px;overflow:hidden;">
                            <div style="height:100%;background:${stage.spent_amount > stage.budget_amount ? '#ef4444' : '#10b981'};width:${Math.min(100, (stage.spent_amount / stage.budget_amount) * 100)}%;"></div>
                        </div>` : ''}
                    </div>

                    ${stage.planned_start_date || stage.actual_start_date ? `
                    <h4 style="margin:14px 0 10px 0;font-size:13px;color:#475569;">📅 زمانبندی</h4>
                    <div style="font-size:11px;color:#64748b;line-height:1.7;">
                        ${stage.planned_start_date ? `<div>برنامه شروع: ${stage.planned_start_date}</div>` : ''}
                        ${stage.planned_end_date   ? `<div>برنامه پایان: ${stage.planned_end_date}</div>` : ''}
                        ${stage.actual_start_date  ? `<div style="color:#3b82f6;">واقعی شروع: ${stage.actual_start_date}</div>` : ''}
                        ${stage.actual_end_date    ? `<div style="color:#10b981;">واقعی پایان: ${stage.actual_end_date}</div>` : ''}
                    </div>` : ''}
                </div>
            </div>

            ${stage.notes ? `
            <div style="padding:0 16px 16px;">
                <div style="background:#fff7ed;padding:10px;border-right:3px solid #f97316;border-radius:6px;font-size:12px;">
                    📝 ${this.escape(stage.notes)}
                </div>
            </div>` : ''}
        </div>`;
    }

    async _toggleTask(taskId, isChecked) {
        try {
            if (isChecked) await this.api.post(`/wf/tasks/${taskId}/complete`, {});
            else           await this.api.put(`/wf/tasks/${taskId}`, { status: 'pending' });
            this._load();
        } catch(e) { alert("خطا: " + (e?.message ?? "")); }
    }

    async _startStage(stage) {
        try {
            await this.api.post(`/wf/stages/${stage.id}/start`, {});
            this._toast("▶️ مرحله شروع شد");
            this._load();
        } catch(e) { alert("خطا: " + (e?.message ?? "")); }
    }

    async _advance(stage) {
        try {
            const res = await this.api.post(`/wf/stages/${stage.id}/advance`, {});
            if (res?.completed) this._toast("🎉 Workflow کامل شد!", "#10b981");
            else                this._toast("⏭️ به مرحله بعد رفت", "#10b981");
            this._activeStageId = res?.next_stage?.id ?? null;
            this._load();
        } catch(e) {
            if (e?.code === 422 || (e?.message && e.message.includes('ناتمام'))) {
                if (confirm(`${e.message}\n\nآیا با force رد کنیم؟`)) {
                    try {
                        await this.api.post(`/wf/stages/${stage.id}/advance?force=1`, {});
                        this._load();
                    } catch(e2) { alert("خطا: " + (e2?.message ?? "")); }
                }
            } else alert("خطا: " + (e?.message ?? ""));
        }
    }

    _editStage(stage) {
        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:460px;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">✏️ ویرایش مرحله «${this.escape(stage.name)}»</div>
            <form>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>برنامه شروع</label>
                        <input name="planned_start_date" type="date" value="${stage.planned_start_date ?? ''}">
                    </div>
                    <div class="acc-form-group"><label>برنامه پایان</label>
                        <input name="planned_end_date" type="date" value="${stage.planned_end_date ?? ''}">
                    </div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>بودجه (ریال)</label>
                        <input name="budget_amount" type="number" value="${stage.budget_amount ?? 0}">
                    </div>
                    <div class="acc-form-group"><label>هزینه شده (ریال)</label>
                        <input name="spent_amount" type="number" value="${stage.spent_amount ?? 0}">
                    </div>
                </div>
                <div class="acc-form-group"><label>یادداشت</label>
                    <textarea name="notes" rows="3">${this.escape(stage.notes ?? '')}</textarea>
                </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 { await this.api.put(`/wf/stages/${stage.id}`, body); close(); this._load(); }
            catch(e) { alert("خطا: " + (e?.message ?? "")); }
        });
    }

    async _showHistory() {
        if (!this._instance) return;
        try {
            const res = await this.api.get(`/wf/instances/${this._instance.id}/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(action) {
        return { create:'🚀', start_stage:'▶️', advance:'⏭️', complete:'🎉' }[action] ?? '🔄';
    }

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

    destroy() {
        this._unsubscribe?.();
        super.destroy?.();
    }
}
