/**
 * PmSchedulesSection.js — برنامه نگهداری پیشگیرانه
 */
import SectionBase from "../../accounting/SectionBase.js";

const PRIORITY = {
    low:    { label:'پایین', color:'#94a3b8' },
    medium: { label:'متوسط', color:'#3b82f6' },
    high:   { label:'بالا',   color:'#f59e0b' },
    urgent: { label:'فوری',  color:'#ef4444' },
};

export default class PmSchedulesSection extends SectionBase {

    constructor(p) { super(p); this._assets = []; }

    async template() {
        return `
        <div class="acc-section-wrap">
            <div class="acc-toolbar">
                <h2 class="acc-section-title">📅 نگهداری پیشگیرانه</h2>
                <div style="display:flex;gap:8px;">
                    <button class="acc-btn acc-btn--warning" data-ref="dueBtn">⏰ سررسید نزدیک</button>
                    <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 data-ref="wrap"><div class="acc-loading">⏳ بارگذاری...</div></div>
        </div>`;
    }

    async afterRender() {
        try { const r = await this.api.get("/assets"); this._assets = r?.data ?? []; } catch {}
        await this._load();
        this.on(this.ref("refreshBtn"), "click", () => this._load());
        this.on(this.ref("addBtn"),     "click", () => this._openModal());
        this.on(this.ref("dueBtn"),     "click", () => this._loadDue());
    }

    async _load() {
        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res = await this.api.get("/assets/pm-schedules");
            this._render(res?.data ?? []);
        } catch { this.ref("wrap").innerHTML = `<div class="acc-error">❌ خطا</div>`; }
    }

    async _loadDue() {
        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری سررسیدها...</div>`;
        try {
            const res = await this.api.get("/assets/pm-schedules/due", { days: 30 });
            this._render(res?.data ?? [], true);
        } catch {}
    }

    _render(rows, dueMode = false) {
        if (!rows.length) {
            this.ref("wrap").innerHTML = `<div class="acc-empty">${dueMode ? '✅ سررسید در راه نیست' : 'برنامه‌ای ثبت نشده'}</div>`;
            return;
        }
        this.ref("wrap").innerHTML = `
        ${dueMode ? `<div style="background:#fef9c3;padding:10px;border-radius:6px;color:#854d0e;margin-bottom:10px;">⏰ ${rows.length} برنامه نگهداری در ۳۰ روز آینده</div>` : ''}
        <table class="acc-table">
            <thead><tr>
                <th>دارایی</th><th>عنوان</th><th>فاصله</th><th>آخرین انجام</th><th>سررسید بعدی</th>
                ${dueMode ? '<th>روز باقیمانده</th>' : ''}
                <th>اولویت</th><th>اقدام</th>
            </tr></thead>
            <tbody>
            ${rows.map(pm => {
                const p = PRIORITY[pm.priority] ?? { label:pm.priority, color:'#64748b' };
                const daysLeft = pm.days_left !== undefined ? parseInt(pm.days_left) : null;
                const overdue = daysLeft !== null && daysLeft <= 0;
                return `<tr ${overdue ? 'style="background:#fef2f2;"' : ''}>
                    <td><b>${this.escape(pm.asset_name ?? '—')}</b><br><small style="color:#94a3b8;">${this.escape(pm.asset_code ?? '')}</small></td>
                    <td>${this.escape(pm.title)}</td>
                    <td><b>${pm.interval_days}</b> روز</td>
                    <td>${pm.last_done_date ?? '—'}</td>
                    <td style="color:${overdue ? '#ef4444' : 'inherit'};font-weight:700;">${pm.next_due_date ?? '—'}</td>
                    ${dueMode ? `<td style="color:${daysLeft <= 7 ? '#ef4444' : '#f59e0b'};font-weight:700;">${daysLeft <= 0 ? 'گذشته' : daysLeft + ' روز'}</td>` : ''}
                    <td><span style="background:${p.color}1a;color:${p.color};padding:1px 8px;border-radius:8px;font-size:11px;font-weight:700;">${p.label}</span></td>
                    <td style="display:flex;gap:4px;">
                        <button class="acc-btn acc-btn--xs" data-edit="${pm.id}">✏️</button>
                        <button class="acc-btn acc-btn--xs" data-wo="${pm.id}" data-asset="${pm.asset_id}" data-title="${this.escape(pm.title)}" style="background:#fef3c7;color:#92400e;">🔧 ساخت WO</button>
                        <button class="acc-btn acc-btn--xs gis-btn--danger" data-del="${pm.id}">🗑️</button>
                    </td>
                </tr>`;
            }).join("")}
            </tbody>
        </table>`;

        this.ref("wrap").querySelectorAll("[data-edit]").forEach(b =>
            b.addEventListener("click", async () => {
                const r = await this.api.get("/assets/pm-schedules");
                const pm = (r?.data ?? []).find(x => x.id == b.dataset.edit);
                if (pm) this._openModal(pm);
            })
        );
        this.ref("wrap").querySelectorAll("[data-del]").forEach(b =>
            b.addEventListener("click", async () => {
                if (!confirm("حذف این برنامه؟")) return;
                try { await this.api.delete(`/assets/pm-schedules/${b.dataset.del}`); this._load(); }
                catch(e) { alert("خطا: " + (e?.message ?? "")); }
            })
        );
        this.ref("wrap").querySelectorAll("[data-wo]").forEach(b =>
            b.addEventListener("click", async () => {
                try {
                    await this.api.post("/assets/work-orders", {
                        asset_id: parseInt(b.dataset.asset),
                        title: b.dataset.title,
                        type: 'preventive',
                        priority: 'medium',
                        pm_schedule_id: parseInt(b.dataset.wo),
                    });
                    alert("✅ درخواست تعمیر ایجاد شد");
                } catch(e) { alert("خطا: " + (e?.message ?? "")); }
            })
        );
    }

    _openModal(pm = null) {
        const isEdit = !!pm;
        const assetOpts = this._assets.map(a =>
            `<option value="${a.id}" ${pm?.asset_id == a.id ? 'selected' : ''}>${this.escape(a.name)} [${this.escape(a.asset_code)}]</option>`).join("");

        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:440px;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">${isEdit ? '✏️ ویرایش' : '➕ برنامه نگهداری جدید'}</div>
            <form>
                <div class="acc-form-group"><label>دارایی *</label>
                    <select name="asset_id" required>${assetOpts || '<option>—</option>'}</select>
                </div>
                <div class="acc-form-group"><label>عنوان *</label>
                    <input name="title" required value="${this.escape(pm?.title ?? '')}" placeholder="مثلاً: تعویض روغن">
                </div>
                <div class="acc-form-group"><label>توضیحات</label>
                    <textarea name="description" rows="2">${this.escape(pm?.description ?? '')}</textarea>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>فاصله (روز) *</label>
                        <input name="interval_days" type="number" min="1" required value="${pm?.interval_days ?? 90}">
                    </div>
                    <div class="acc-form-group"><label>هزینه تخمینی (﷼)</label>
                        <input name="estimated_cost" type="number" min="0" value="${pm?.estimated_cost ?? 0}">
                    </div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>آخرین انجام</label>
                        <input name="last_done_date" type="date" value="${pm?.last_done_date ?? ''}">
                    </div>
                    <div class="acc-form-group"><label>اولویت</label>
                        <select name="priority">
                            ${Object.entries(PRIORITY).map(([k,v]) => `<option value="${k}" ${pm?.priority === k ? 'selected' : ''}>${v.label}</option>`).join("")}
                        </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">ذخیره</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 {
                if (isEdit) await this.api.put(`/assets/pm-schedules/${pm.id}`, body);
                else        await this.api.post("/assets/pm-schedules", body);
                close(); this._load();
            } catch(e) { alert("خطا: " + (e?.message ?? "")); }
        });
    }

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