/**
 * TasksSection.js — مدیریت وظایف (WBS + Tasks + Progress)
 */
import SectionBase from "../../accounting/SectionBase.js";

const STATUS_LABELS = {
    not_started: { label: "شروع نشده",   color: "#6b7280", bg: "#f3f4f6" },
    in_progress:  { label: "در حال انجام", color: "#2563eb", bg: "#eff6ff" },
    completed:    { label: "تکمیل",        color: "#059669", bg: "#ecfdf5" },
    on_hold:      { label: "متوقف",        color: "#d97706", bg: "#fffbeb" },
    cancelled:    { label: "لغو",          color: "#dc2626", bg: "#fef2f2" },
};

const PRIORITY_LABELS = {
    low:      { label: "کم",      color: "#6b7280" },
    medium:   { label: "متوسط",   color: "#2563eb" },
    high:     { label: "بالا",    color: "#d97706" },
    critical: { label: "بحرانی",  color: "#dc2626" },
};

export default class TasksSection extends SectionBase {

    constructor(props = {}) {
        super(props);
        this.cpmView   = props.cpmView ?? null;
        this._projectId = null;
        this._tasks     = [];
        this._wbs       = [];
        this._members   = [];
        this._deps      = [];
    }

    async template() {
        return `
            <div class="cpm-section-wrap">
                <div class="cpm-section-notice" data-ref="notice" style="display:none">
                    <span>⚠️ لطفاً ابتدا یک پروژه از تب «پروژه‌ها» انتخاب کنید.</span>
                </div>
                <div data-ref="content" style="display:none">
                    <div class="cpm-toolbar">
                        <button class="acc-btn acc-btn--primary acc-btn--sm" data-ref="addTaskBtn">+ وظیفه جدید</button>
                        <button class="acc-btn acc-btn--secondary acc-btn--sm" data-ref="addWbsBtn">+ WBS</button>
                        <select data-ref="wbsFilter" style="padding:7px 12px;border:1.5px solid #d1d5db;border-radius:8px;font-size:13px;">
                            <option value="">همه WBS</option>
                        </select>
                        <select data-ref="statusFilter" style="padding:7px 12px;border:1.5px solid #d1d5db;border-radius:8px;font-size:13px;">
                            <option value="">همه وضعیت‌ها</option>
                            <option value="not_started">شروع نشده</option>
                            <option value="in_progress">در حال انجام</option>
                            <option value="completed">تکمیل</option>
                            <option value="on_hold">متوقف</option>
                            <option value="cancelled">لغو</option>
                        </select>
                    </div>
                    <div data-ref="tasksWrap"></div>
                </div>
            </div>
        `;
    }

    async afterRender() {
        this.ref("notice").style.display = "flex";
    }

    async onProjectChange(project) {
        this._projectId = project?.id ?? null;
        if (!this._projectId) {
            this.ref("notice").style.display = "flex";
            this.ref("content").style.display = "none";
            return;
        }
        this.ref("notice").style.display = "none";
        this.ref("content").style.display = "block";

        this.on(this.ref("addTaskBtn"), "click", () => this._openTaskForm(null));
        this.on(this.ref("addWbsBtn"),  "click", () => this._openWbsForm(null));
        this.on(this.ref("wbsFilter"),   "change", () => this._renderTasks());
        this.on(this.ref("statusFilter"),"change", () => this._renderTasks());

        await this._loadAll();
    }

    async _loadAll() {
        const wrap = this.ref("tasksWrap");
        wrap.innerHTML = `<div class="cpm-loading"><div class="acc-spinner"></div></div>`;
        try {
            const res = await this.api.get(`/pc/projects/${this._projectId}/workspace`, { scope: "tasks" });
            this._wbs     = res?.wbs            ?? [];
            this._tasks   = res?.tasks          ?? [];
            this._members = res?.members        ?? [];
            this._deps    = res?.dependencies   ?? [];
            this._populateWbsFilter();
            this._renderTasks();
        } catch {
            wrap.innerHTML = `<div class="acc-empty">خطا در بارگذاری وظایف</div>`;
        }
    }

    _populateWbsFilter() {
        const sel = this.ref("wbsFilter");
        if (!sel) return;
        sel.innerHTML = `<option value="">همه WBS</option>` +
            this._wbs.map(w => `<option value="${w.id}">${this.escape(w.code ? w.code + " — " : "")}${this.escape(w.name)}</option>`).join("");
    }

    _renderTasks() {
        const wrap     = this.ref("tasksWrap");
        const wbsFilt  = this.ref("wbsFilter")?.value;
        const statFilt = this.ref("statusFilter")?.value;

        let tasks = this._tasks;
        if (wbsFilt)  tasks = tasks.filter(t => String(t.wbs_id) === wbsFilt);
        if (statFilt) tasks = tasks.filter(t => t.status === statFilt);

        if (!tasks.length) {
            wrap.innerHTML = `<div class="acc-empty">وظیفه‌ای یافت نشد.</div>`;
            return;
        }

        // Group by WBS
        const wbsMap = {};
        this._wbs.forEach(w => { wbsMap[w.id] = w; });

        const groups = {};
        tasks.forEach(t => {
            const key = t.wbs_id ?? "0";
            if (!groups[key]) groups[key] = { wbs: wbsMap[key] ?? null, tasks: [] };
            groups[key].tasks.push(t);
        });

        wrap.innerHTML = "";
        Object.entries(groups).forEach(([k, g]) => {
            const grpEl = document.createElement("div");
            grpEl.className = "cpm-wbs-group";
            const wbsTitle = g.wbs
                ? `<span class="cpm-wbs-code">${this.escape(g.wbs.code || "")}</span> ${this.escape(g.wbs.name)}`
                : "بدون WBS";

            grpEl.innerHTML = `
                <div class="cpm-wbs-group__header">
                    <span class="cpm-wbs-icon">📂</span>
                    <span>${wbsTitle}</span>
                    ${g.wbs ? `<button class="acc-btn acc-btn--secondary acc-btn--xs" data-wbs-edit="${g.wbs.id}">ویرایش WBS</button>` : ""}
                </div>
                <div class="cpm-task-list"></div>
            `;

            if (g.wbs) {
                grpEl.querySelector(`[data-wbs-edit]`)?.addEventListener("click", () => this._openWbsForm(g.wbs));
            }

            const taskList = grpEl.querySelector(".cpm-task-list");
            g.tasks.forEach(t => taskList.appendChild(this._buildTaskRow(t)));
            wrap.appendChild(grpEl);
        });
    }

    _buildTaskRow(t) {
        const st  = STATUS_LABELS[t.status]   ?? { label: t.status,   color: "#64748b", bg: "#f1f5f9" };
        const pri = PRIORITY_LABELS[t.priority] ?? { label: t.priority, color: "#64748b" };
        const pct = parseFloat(t.progress ?? 0).toFixed(0);
        const member = this._members.find(m => m.id == t.assigned_member_id);

        const row = document.createElement("div");
        row.className = "cpm-task-row" + (t.is_critical ? " cpm-task-row--critical" : "");
        row.innerHTML = `
            <div class="cpm-task-row__info">
                <div class="cpm-task-row__top">
                    <span class="cpm-task-code">${this.escape(t.code || "T-" + t.id)}</span>
                    ${t.is_critical ? `<span class="cpm-badge cpm-badge--critical" title="مسیر بحرانی">🔴 بحرانی</span>` : ""}
                    <span class="cpm-task-name">${this.escape(t.name)}</span>
                    <span class="cpm-status-badge" style="background:${st.bg};color:${st.color}">${st.label}</span>
                    <span style="font-size:11px;font-weight:700;color:${pri.color}">${pri.label}</span>
                </div>
                <div class="cpm-task-row__meta">
                    ${t.start_date ? `📅 ${t.start_date} → ${t.end_date || "؟"}` : ""}
                    ${t.duration ? ` | ⏱ ${t.duration} ${t.duration_unit === "day" ? "روز" : t.duration_unit === "hour" ? "ساعت" : "هفته"}` : ""}
                    ${member ? ` | 👤 ${this.escape(member.name)}` : ""}
                </div>
                <div class="cpm-task-progress-row">
                    <input type="range" class="cpm-progress-slider" min="0" max="100" value="${pct}" data-tid="${t.id}">
                    <span class="cpm-progress-pct">${pct}٪</span>
                </div>
            </div>
            <div class="cpm-task-row__actions">
                <button class="acc-btn acc-btn--secondary acc-btn--xs" data-action="edit">ویرایش</button>
                <button class="acc-btn acc-btn--secondary acc-btn--xs" data-action="logs">لاگ</button>
                <button class="acc-btn acc-btn--danger acc-btn--xs"    data-action="del">حذف</button>
            </div>
        `;

        // Progress slider
        const slider = row.querySelector(".cpm-progress-slider");
        const pctLabel = row.querySelector(".cpm-progress-pct");
        let debounce;
        slider.addEventListener("input", () => {
            pctLabel.textContent = slider.value + "٪";
        });
        slider.addEventListener("change", () => {
            clearTimeout(debounce);
            debounce = setTimeout(() => this._updateProgress(t, parseInt(slider.value)), 400);
        });

        row.querySelector("[data-action='edit']").addEventListener("click", () => this._openTaskForm(t));
        row.querySelector("[data-action='logs']").addEventListener("click", () => this._showLogs(t));
        row.querySelector("[data-action='del']").addEventListener("click",  () => this._deleteTask(t));
        return row;
    }

    async _updateProgress(t, newVal) {
        try {
            await this.api.post(`/pc/tasks/${t.id}/progress`, { progress: newVal });
            t.progress = newVal;
        } catch (err) { alert("خطا: " + (err?.message ?? "")); }
    }

    /* ── Task Form ──────────────────────────────────────────────── */

    _openTaskForm(t = null) {
        const isEdit = !!t;
        const wbsOpts = this._wbs.map(w =>
            `<option value="${w.id}" ${t?.wbs_id == w.id ? "selected" : ""}>${this.escape(w.name)}</option>`
        ).join("");
        const memberOpts = this._members.map(m =>
            `<option value="${m.id}" ${t?.assigned_member_id == m.id ? "selected" : ""}>${this.escape(m.name)}</option>`
        ).join("");

        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
            <div class="acc-modal" style="max-width:620px;">
                <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(t?.code || "")}">
                        </div>
                        <div class="acc-form-group">
                            <label>نام وظیفه *</label>
                            <input name="name" value="${this.escape(t?.name || "")}" required>
                        </div>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group">
                            <label>WBS</label>
                            <select name="wbs_id">
                                <option value="">— بدون WBS —</option>
                                ${wbsOpts}
                            </select>
                        </div>
                        <div class="acc-form-group">
                            <label>نوع</label>
                            <select name="type">
                                <option value="task"      ${t?.type==="task"?"selected":""}>وظیفه</option>
                                <option value="milestone" ${t?.type==="milestone"?"selected":""}>نقطه عطف</option>
                                <option value="summary"   ${t?.type==="summary"?"selected":""}>خلاصه</option>
                            </select>
                        </div>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group">
                            <label>وضعیت</label>
                            <select name="status">
                                <option value="not_started" ${t?.status==="not_started"?"selected":""}>شروع نشده</option>
                                <option value="in_progress"  ${t?.status==="in_progress"?"selected":""}>در حال انجام</option>
                                <option value="completed"    ${t?.status==="completed"?"selected":""}>تکمیل</option>
                                <option value="on_hold"      ${t?.status==="on_hold"?"selected":""}>متوقف</option>
                                <option value="cancelled"    ${t?.status==="cancelled"?"selected":""}>لغو</option>
                            </select>
                        </div>
                        <div class="acc-form-group">
                            <label>اولویت</label>
                            <select name="priority">
                                <option value="low"      ${t?.priority==="low"?"selected":""}>کم</option>
                                <option value="medium"   ${t?.priority==="medium"?"selected":""}>متوسط</option>
                                <option value="high"     ${t?.priority==="high"?"selected":""}>بالا</option>
                                <option value="critical" ${t?.priority==="critical"?"selected":""}>بحرانی</option>
                            </select>
                        </div>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group">
                            <label>مدت (روز/ساعت/هفته)</label>
                            <input type="number" name="duration" value="${this.escape(t?.duration || "0")}" min="0">
                        </div>
                        <div class="acc-form-group">
                            <label>واحد مدت</label>
                            <select name="duration_unit">
                                <option value="day"  ${t?.duration_unit==="day"?"selected":""}>روز</option>
                                <option value="hour" ${t?.duration_unit==="hour"?"selected":""}>ساعت</option>
                                <option value="week" ${t?.duration_unit==="week"?"selected":""}>هفته</option>
                            </select>
                        </div>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group">
                            <label>تاریخ شروع</label>
                            <input type="date" name="start_date" value="${this.escape(t?.start_date || "")}">
                        </div>
                        <div class="acc-form-group">
                            <label>تاریخ پایان</label>
                            <input type="date" name="end_date" value="${this.escape(t?.end_date || "")}">
                        </div>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group">
                            <label>پیشرفت (٪)</label>
                            <input type="number" name="progress" value="${this.escape(t?.progress || "0")}" min="0" max="100">
                        </div>
                        <div class="acc-form-group">
                            <label>عضو مسئول</label>
                            <select name="assigned_member_id">
                                <option value="">— بدون تخصیص —</option>
                                ${memberOpts}
                            </select>
                        </div>
                    </div>
                    <div class="acc-form-group">
                        <label>توضیحات</label>
                        <textarea name="description" rows="2">${this.escape(t?.description || "")}</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">${isEdit ? "ذخیره" : "افزودن"}</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", ev => { if (ev.target === ov) close(); });
        ov.querySelector("form").addEventListener("submit", async ev => {
            ev.preventDefault();
            const body = Object.fromEntries(new FormData(ev.target).entries());
            if (!body.wbs_id) delete body.wbs_id;
            if (!body.assigned_member_id) delete body.assigned_member_id;
            body.project_id = this._projectId;
            const btn = ev.target.querySelector("[type='submit']");
            btn.disabled = true; btn.textContent = "در حال ذخیره...";
            try {
                if (isEdit) await this.api.put(`/pc/tasks/${t.id}`, body);
                else        await this.api.post(`/pc/projects/${this._projectId}/tasks`, body);
                close(); await this._loadAll();
            } catch (err) {
                alert("خطا: " + (err?.message ?? ""));
                btn.disabled = false; btn.textContent = isEdit ? "ذخیره" : "افزودن";
            }
        });
    }

    /* ── WBS Form ───────────────────────────────────────────────── */

    _openWbsForm(w = null) {
        const isEdit = !!w;
        const parentOpts = this._wbs
            .filter(x => x.id !== w?.id)
            .map(x => `<option value="${x.id}" ${w?.parent_id == x.id ? "selected" : ""}>${this.escape(x.name)}</option>`)
            .join("");

        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
            <div class="acc-modal" style="max-width:480px;">
                <button class="acc-modal__close">✕</button>
                <div class="acc-modal__title">${isEdit ? "ویرایش WBS" : "WBS جدید"}</div>
                <form>
                    <div class="doc-form-row">
                        <div class="acc-form-group">
                            <label>کد WBS</label>
                            <input name="code" value="${this.escape(w?.code || "")}">
                        </div>
                        <div class="acc-form-group">
                            <label>نام WBS *</label>
                            <input name="name" value="${this.escape(w?.name || "")}" required>
                        </div>
                    </div>
                    <div class="acc-form-group">
                        <label>WBS والد</label>
                        <select name="parent_id">
                            <option value="">— سطح اول —</option>
                            ${parentOpts}
                        </select>
                    </div>
                    <div class="acc-form-group">
                        <label>توضیحات</label>
                        <textarea name="description" rows="2">${this.escape(w?.description || "")}</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">${isEdit ? "ذخیره" : "افزودن"}</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", ev => { if (ev.target === ov) close(); });
        ov.querySelector("form").addEventListener("submit", async ev => {
            ev.preventDefault();
            const body = Object.fromEntries(new FormData(ev.target).entries());
            if (!body.parent_id) delete body.parent_id;
            const btn = ev.target.querySelector("[type='submit']");
            btn.disabled = true; btn.textContent = "در حال ذخیره...";
            try {
                if (isEdit) await this.api.put(`/pc/wbs/${w.id}`, body);
                else        await this.api.post(`/pc/projects/${this._projectId}/wbs`, body);
                close(); await this._loadAll();
            } catch (err) {
                alert("خطا: " + (err?.message ?? ""));
                btn.disabled = false; btn.textContent = isEdit ? "ذخیره" : "افزودن";
            }
        });
    }

    /* ── Task Logs ──────────────────────────────────────────────── */

    async _showLogs(t) {
        let logs = [];
        try {
            const r = await this.api.get(`/pc/tasks/${t.id}/logs`);
            logs = r?.data ?? [];
        } catch { /* ignore */ }

        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        const rows = logs.length
            ? logs.map(l => `
                <tr>
                    <td>${l.created_at?.slice(0,16) ?? ""}</td>
                    <td>${this.escape(l.reporter_name || "—")}</td>
                    <td>${l.old_progress}٪ → ${l.new_progress}٪</td>
                    <td>${this.escape(l.old_status||"")} → ${this.escape(l.new_status||"")}</td>
                    <td>${this.escape(l.note || "")}</td>
                </tr>`).join("")
            : `<tr><td colspan="5" style="text-align:center;padding:20px;color:#94a3b8;">لاگی ثبت نشده</td></tr>`;

        ov.innerHTML = `
            <div class="acc-modal" style="max-width:700px;">
                <button class="acc-modal__close">✕</button>
                <div class="acc-modal__title">لاگ پیشرفت: ${this.escape(t.name)}</div>
                <table class="acc-table" style="width:100%;font-size:12px;">
                    <thead><tr><th>تاریخ</th><th>گزارش‌دهنده</th><th>پیشرفت</th><th>وضعیت</th><th>یادداشت</th></tr></thead>
                    <tbody>${rows}</tbody>
                </table>
                <div class="acc-modal__actions"><button class="acc-btn acc-btn--secondary" data-action="close">بستن</button></div>
            </div>`;
        document.body.appendChild(ov);
        ov.querySelector(".acc-modal__close").addEventListener("click", () => ov.remove());
        ov.querySelector("[data-action='close']").addEventListener("click", () => ov.remove());
        ov.addEventListener("click", ev => { if (ev.target === ov) ov.remove(); });
    }

    async _deleteTask(t) {
        if (!confirm(`حذف وظیفه «${t.name}»؟`)) return;
        try { await this.api.delete(`/pc/tasks/${t.id}`); await this._loadAll(); }
        catch (err) { alert("خطا: " + (err?.message ?? "")); }
    }
}
