/**
 * ResourcesSection.js — مدیریت منابع و تخصیص منابع به وظایف
 */
import SectionBase from "../../accounting/SectionBase.js";

const TYPE_LABELS = {
    human:     { label: "انسانی",    icon: "👤", color: "#2563eb", bg: "#eff6ff" },
    equipment: { label: "تجهیزات",   icon: "⚙️", color: "#7c3aed", bg: "#f5f3ff" },
    material:  { label: "مواد",       icon: "📦", color: "#d97706", bg: "#fffbeb" },
    other:     { label: "سایر",       icon: "🔧", color: "#6b7280", bg: "#f3f4f6" },
};

export default class ResourcesSection extends SectionBase {

    constructor(props = {}) {
        super(props);
        this.cpmView    = props.cpmView ?? null;
        this._projectId = null;
        this._resources = [];
        this._tasks     = [];
        this._assignments = [];
        this._tab       = "resources"; // "resources" | "assignments"
    }

    async template() {
        return `
            <div class="cpm-section-wrap">
                <div class="cpm-section-notice" data-ref="notice">
                    <span>⚠️ لطفاً ابتدا یک پروژه از تب «پروژه‌ها» انتخاب کنید.</span>
                </div>
                <div data-ref="content" style="display:none">
                    <div class="cpm-sub-tabs" data-ref="subTabs">
                        <button class="cpm-sub-tab cpm-sub-tab--active" data-tab="resources">👷 منابع</button>
                        <button class="cpm-sub-tab" data-tab="assignments">🔗 تخصیص منابع</button>
                    </div>
                    <div data-ref="tabContent"></div>
                </div>
            </div>
        `;
    }

    async afterRender() {
        // notice shown by default
    }

    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.ref("subTabs").querySelectorAll(".cpm-sub-tab").forEach(btn => {
            this.on(btn, "click", () => this._switchTab(btn.dataset.tab));
        });

        await this._loadAll();
        this._renderTab();
    }

    async _loadAll() {
        try {
            const res = await this.api.get(`/pc/projects/${this._projectId}/workspace`, { scope: "resources" });
            this._resources   = res?.resources   ?? [];
            this._tasks       = res?.tasks       ?? [];
            this._assignments = res?.assignments ?? [];
        } catch { /* handled in render */ }
    }

    _switchTab(tab) {
        this._tab = tab;
        this.ref("subTabs").querySelectorAll(".cpm-sub-tab").forEach(btn =>
            btn.classList.toggle("cpm-sub-tab--active", btn.dataset.tab === tab)
        );
        this._renderTab();
    }

    _renderTab() {
        if (this._tab === "resources")   this._renderResources();
        else                              this._renderAssignments();
    }

    /* ── Resources list ─────────────────────────────────────────── */

    _renderResources() {
        const wrap = this.ref("tabContent");
        wrap.innerHTML = `
            <div class="cpm-toolbar" style="margin-top:12px">
                <button class="acc-btn acc-btn--primary acc-btn--sm" id="addResBtn">+ منبع جدید</button>
            </div>
            <div class="cpm-res-grid" id="resGrid"></div>
        `;
        wrap.querySelector("#addResBtn").addEventListener("click", () => this._openResourceForm(null));
        this._fillResourceGrid(wrap.querySelector("#resGrid"));
    }

    _fillResourceGrid(grid) {
        if (!this._resources.length) {
            grid.innerHTML = `<div class="acc-empty">منبعی تعریف نشده است.</div>`;
            return;
        }
        grid.innerHTML = "";
        this._resources.forEach(r => {
            const t = TYPE_LABELS[r.type] ?? TYPE_LABELS.other;
            const card = document.createElement("div");
            card.className = "cpm-res-card";
            card.innerHTML = `
                <div class="cpm-res-card__type" style="background:${t.bg};color:${t.color}">
                    ${t.icon} ${t.label}
                </div>
                <div class="cpm-res-card__name">${this.escape(r.name)}</div>
                ${r.code ? `<div class="cpm-res-card__code">${this.escape(r.code)}</div>` : ""}
                <div class="cpm-res-card__meta">
                    ${r.unit ? `واحد: ${this.escape(r.unit)}` : ""}
                    ${r.cost_per_unit > 0 ? ` | نرخ: ${Number(r.cost_per_unit).toLocaleString('fa-IR')} ${r.currency}` : ""}
                </div>
                <div class="cpm-res-card__actions">
                    <button class="acc-btn acc-btn--secondary acc-btn--xs" data-action="edit">ویرایش</button>
                    <button class="acc-btn acc-btn--danger acc-btn--xs"    data-action="del">حذف</button>
                </div>
            `;
            card.querySelector("[data-action='edit']").addEventListener("click", () => this._openResourceForm(r));
            card.querySelector("[data-action='del']").addEventListener("click",  () => this._deleteResource(r));
            grid.appendChild(card);
        });
    }

    _openResourceForm(r = null) {
        const isEdit = !!r;
        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 ? "ویرایش منبع" : "منبع جدید"}</div>
                <form>
                    <div class="doc-form-row">
                        <div class="acc-form-group">
                            <label>کد منبع</label>
                            <input name="code" value="${this.escape(r?.code || "")}">
                        </div>
                        <div class="acc-form-group">
                            <label>نام منبع *</label>
                            <input name="name" value="${this.escape(r?.name || "")}" required>
                        </div>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group">
                            <label>نوع</label>
                            <select name="type">
                                <option value="human"     ${r?.type==="human"?"selected":""}>انسانی</option>
                                <option value="equipment" ${r?.type==="equipment"?"selected":""}>تجهیزات</option>
                                <option value="material"  ${r?.type==="material"?"selected":""}>مواد</option>
                                <option value="other"     ${r?.type==="other"?"selected":""}>سایر</option>
                            </select>
                        </div>
                        <div class="acc-form-group">
                            <label>واحد</label>
                            <input name="unit" value="${this.escape(r?.unit || "")}" placeholder="نفر/روز، کیلوگرم...">
                        </div>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group">
                            <label>نرخ هر واحد (ریال)</label>
                            <input type="number" name="cost_per_unit" value="${this.escape(r?.cost_per_unit || "0")}" min="0">
                        </div>
                        <div class="acc-form-group">
                            <label>ارز</label>
                            <select name="currency">
                                <option value="IRR" ${r?.currency==="IRR"?"selected":""}>ریال</option>
                                <option value="USD" ${r?.currency==="USD"?"selected":""}>دلار</option>
                            </select>
                        </div>
                    </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());
            const btn = ev.target.querySelector("[type='submit']");
            btn.disabled = true; btn.textContent = "در حال ذخیره...";
            try {
                if (isEdit) await this.api.put(`/pc/resources/${r.id}`, body);
                else        await this.api.post(`/pc/projects/${this._projectId}/resources`, body);
                close();
                await this._loadAll();
                this._renderTab();
            } catch (err) {
                alert("خطا: " + (err?.message ?? ""));
                btn.disabled = false; btn.textContent = isEdit ? "ذخیره" : "افزودن";
            }
        });
    }

    async _deleteResource(r) {
        if (!confirm(`حذف منبع «${r.name}»؟`)) return;
        try {
            await this.api.delete(`/pc/resources/${r.id}`);
            await this._loadAll();
            this._renderTab();
        } catch (err) { alert("خطا: " + (err?.message ?? "")); }
    }

    /* ── Assignments ────────────────────────────────────────────── */

    async _renderAssignments() {
        const wrap = this.ref("tabContent");

        const assignments = this._assignments;

        const resMap  = {};
        const taskMap = {};
        this._resources.forEach(r => { resMap[r.id]  = r; });
        this._tasks.forEach(t =>     { taskMap[t.id] = t; });

        const taskOpts  = this._tasks.map(t =>
            `<option value="${t.id}">${this.escape(t.code ? t.code + " — " : "")}${this.escape(t.name)}</option>`
        ).join("");
        const resOpts = this._resources.map(r =>
            `<option value="${r.id}">${this.escape(r.name)} (${TYPE_LABELS[r.type]?.label ?? r.type})</option>`
        ).join("");

        const rows = assignments.length
            ? assignments.map(a => {
                const res  = resMap[a.resource_id];
                const task = taskMap[a.task_id];
                const t    = TYPE_LABELS[res?.type] ?? TYPE_LABELS.other;
                return `
                    <tr>
                        <td>${this.escape(task?.name ?? "#" + a.task_id)}</td>
                        <td>
                            <span class="cpm-badge" style="background:${t.bg};color:${t.color}">${t.icon} ${this.escape(res?.name ?? "#" + a.resource_id)}</span>
                        </td>
                        <td>${a.quantity} ${this.escape(res?.unit || "")}</td>
                        <td>${Number(a.cost_per_unit).toLocaleString('fa-IR')}</td>
                        <td><strong>${Number(a.total_cost).toLocaleString('fa-IR')}</strong></td>
                        <td>${this.escape(a.notes || "")}</td>
                        <td>
                            <button class="acc-btn acc-btn--danger acc-btn--xs" data-del="${a.id}">حذف</button>
                        </td>
                    </tr>`;
            }).join("")
            : `<tr><td colspan="7" style="text-align:center;padding:20px;color:#94a3b8;">تخصیصی ثبت نشده</td></tr>`;

        wrap.innerHTML = `
            <div style="margin-top:12px">
                <div class="cpm-toolbar">
                    <button class="acc-btn acc-btn--primary acc-btn--sm" id="addAssignBtn">+ تخصیص جدید</button>
                </div>
                <table class="acc-table" style="width:100%;margin-top:10px">
                    <thead>
                        <tr>
                            <th>وظیفه</th><th>منبع</th><th>مقدار</th>
                            <th>نرخ واحد</th><th>هزینه کل</th><th>یادداشت</th><th></th>
                        </tr>
                    </thead>
                    <tbody>${rows}</tbody>
                </table>
            </div>`;

        wrap.querySelector("#addAssignBtn").addEventListener("click", () =>
            this._openAssignmentForm(taskOpts, resOpts)
        );
        wrap.querySelectorAll("[data-del]").forEach(btn =>
            btn.addEventListener("click", () => this._deleteAssignment(btn.dataset.del))
        );
    }

    _openAssignmentForm(taskOpts, resOpts) {
        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">تخصیص منبع به وظیفه</div>
                <form>
                    <div class="acc-form-group">
                        <label>وظیفه *</label>
                        <select name="task_id" required><option value="">انتخاب کنید</option>${taskOpts}</select>
                    </div>
                    <div class="acc-form-group">
                        <label>منبع *</label>
                        <select name="resource_id" required><option value="">انتخاب کنید</option>${resOpts}</select>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group">
                            <label>مقدار / تعداد</label>
                            <input type="number" name="quantity" value="1" min="0" step="0.01">
                        </div>
                        <div class="acc-form-group">
                            <label>نرخ واحد (ریال)</label>
                            <input type="number" name="cost_per_unit" value="0" min="0">
                        </div>
                    </div>
                    <div class="acc-form-group">
                        <label>یادداشت</label>
                        <textarea name="notes" rows="2"></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", ev => { if (ev.target === ov) close(); });
        ov.querySelector("form").addEventListener("submit", async ev => {
            ev.preventDefault();
            const body = Object.fromEntries(new FormData(ev.target).entries());
            const qty  = parseFloat(body.quantity || 1);
            const rate = parseFloat(body.cost_per_unit || 0);
            body.total_cost = (qty * rate).toFixed(4);
            const btn = ev.target.querySelector("[type='submit']");
            btn.disabled = true; btn.textContent = "در حال ذخیره...";
            try {
                await this.api.post(`/pc/projects/${this._projectId}/assignments`, body);
                close();
                await this._loadAll();
                this._renderAssignments();
            } catch (err) {
                alert("خطا: " + (err?.message ?? ""));
                btn.disabled = false; btn.textContent = "ثبت تخصیص";
            }
        });
    }

    async _deleteAssignment(id) {
        if (!confirm("حذف این تخصیص؟")) return;
        try {
            await this.api.delete(`/pc/assignments/${id}`);
            await this._loadAll();
            this._renderAssignments();
        } catch (err) { alert("خطا: " + (err?.message ?? "")); }
    }
}
