/**
 * WorkOrdersSection.js — درخواست‌های تعمیر
 */
import SectionBase from "../../accounting/SectionBase.js";

const STATUS = {
    open:        { label:'باز',         color:'#3b82f6' },
    in_progress: { label:'در حال انجام', color:'#f59e0b' },
    waiting:     { label:'منتظر قطعه',   color:'#8b5cf6' },
    closed:      { label:'بسته شده',     color:'#10b981' },
    cancelled:   { label:'لغو شده',      color:'#94a3b8' },
};

const TYPE = {
    corrective:'🔧 اصلاحی', preventive:'📅 پیشگیرانه',
    inspection:'🔍 بازرسی', emergency:'🚨 اضطراری',
};

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

export default class WorkOrdersSection extends SectionBase {

    async template() {
        return `
        <div class="acc-section-wrap">
            <div class="acc-toolbar">
                <h2 class="acc-section-title">🔧 درخواست‌های تعمیر</h2>
                <div style="display:flex;gap:8px;">
                    <select data-ref="statusFilter" class="acc-input">
                        <option value="">همه وضعیت‌ها</option>
                        ${Object.entries(STATUS).map(([k,v]) => `<option value="${k}">${v.label}</option>`).join("")}
                    </select>
                    <select data-ref="typeFilter" class="acc-input">
                        <option value="">همه نوع‌ها</option>
                        ${Object.entries(TYPE).map(([k,v]) => `<option value="${k}">${v}</option>`).join("")}
                    </select>
                    <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() {
        await this._load();
        this.on(this.ref("refreshBtn"),   "click",  () => this._load());
        this.on(this.ref("statusFilter"), "change", () => this._load());
        this.on(this.ref("typeFilter"),   "change", () => this._load());
    }

    async _load() {
        const params = {};
        const s = this.ref("statusFilter")?.value;
        const t = this.ref("typeFilter")?.value;
        if (s) params.status = s;
        if (t) params.type   = t;

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

    _render(rows) {
        if (!rows.length) { this.ref("wrap").innerHTML = `<div class="acc-empty">درخواست تعمیری یافت نشد</div>`; return; }
        this.ref("wrap").innerHTML = `
        <table class="acc-table">
            <thead><tr>
                <th>شماره</th><th>دارایی</th><th>عنوان</th><th>نوع</th>
                <th>اولویت</th><th>وضعیت</th><th>تخصیص</th><th>هزینه</th><th>اقدام</th>
            </tr></thead>
            <tbody>
            ${rows.map(w => {
                const s = STATUS[w.status]    ?? { label:w.status, color:'#64748b' };
                const p = PRIORITY[w.priority] ?? { label:w.priority, color:'#64748b' };
                return `<tr>
                    <td><b style="font-family:monospace;">${this.escape(w.wo_no)}</b></td>
                    <td>
                        <div>${this.escape(w.asset_name ?? '—')}</div>
                        <small style="color:#94a3b8;">${this.escape(w.asset_code ?? '')}</small>
                    </td>
                    <td>${this.escape(w.title)}</td>
                    <td><small>${TYPE[w.type] ?? w.type}</small></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><span style="background:${s.color}1a;color:${s.color};padding:2px 8px;border-radius:10px;font-size:11px;font-weight:700;">${s.label}</span></td>
                    <td><small>${this.escape(w.assigned_name ?? '—')}</small></td>
                    <td>${parseFloat(w.total_cost) > 0 ? '<b>'+this._fmt(w.total_cost)+'</b>' : '—'}</td>
                    <td><button class="acc-btn acc-btn--xs acc-btn--primary" data-view="${w.id}">👁️ مدیریت</button></td>
                </tr>`;
            }).join("")}
            </tbody>
        </table>`;

        this.ref("wrap").querySelectorAll("[data-view]").forEach(b =>
            b.addEventListener("click", () => this._viewWo(parseInt(b.dataset.view)))
        );
    }

    async _viewWo(id) {
        try {
            const res = await this.api.get(`/assets/work-orders/${id}`);
            this._renderWoModal(res?.data);
        } catch(e) { alert("خطا: " + (e?.message ?? "")); }
    }

    _renderWoModal(w) {
        const s = STATUS[w.status]    ?? { label:w.status, color:'#64748b' };
        const items = w.items ?? [];
        const itemsTotal = items.reduce((sum, i) => sum + parseFloat(i.total_cost), 0);

        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:680px;max-height:92vh;overflow-y:auto;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">🔧 ${this.escape(w.wo_no)}</div>

            <div style="background:${s.color}1a;border-right:4px solid ${s.color};padding:10px;border-radius:6px;margin-bottom:14px;">
                <div style="font-weight:700;color:${s.color};">${s.label}</div>
                <div style="font-size:12px;color:#64748b;margin-top:4px;">${TYPE[w.type] ?? w.type}</div>
            </div>

            <h4 style="margin:0 0 6px 0;font-size:13px;">📦 دارایی: ${this.escape(w.asset_name)}</h4>
            <div style="font-size:12px;color:#64748b;margin-bottom:14px;"><b>عنوان:</b> ${this.escape(w.title)}</div>

            <form id="wo-form">
                <div class="acc-form-group"><label>توضیح مشکل</label>
                    <textarea name="problem_desc" rows="2">${this.escape(w.problem_desc ?? '')}</textarea>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>وضعیت</label>
                        <select name="status">
                            ${Object.entries(STATUS).map(([k,v]) => `<option value="${k}" ${w.status === k ? 'selected' : ''}>${v.label}</option>`).join("")}
                        </select>
                    </div>
                    <div class="acc-form-group"><label>تخصیص به</label>
                        <input name="assigned_name" value="${this.escape(w.assigned_name ?? '')}">
                    </div>
                </div>

                <h4 style="margin:12px 0 6px 0;font-size:13px;">📦 قطعات/کار:</h4>
                <div id="wo-items">
                    ${items.map((i, idx) => this._renderItemRow(i, idx)).join("") || '<div style="color:#94a3b8;font-size:12px;">ردیفی نیست</div>'}
                </div>
                <button type="button" class="acc-btn acc-btn--xs" id="wo-add-item">➕ افزودن ردیف</button>

                <div class="doc-form-row" style="margin-top:14px;">
                    <div class="acc-form-group"><label>هزینه دستمزد (﷼)</label>
                        <input name="labor_cost" type="number" value="${w.labor_cost ?? 0}">
                    </div>
                    <div class="acc-form-group"><label>زمان توقف (ساعت)</label>
                        <input name="downtime_hours" type="number" step="0.1" value="${w.downtime_hours ?? 0}">
                    </div>
                </div>

                <div class="acc-form-group"><label>توضیح راه‌حل</label>
                    <textarea name="solution_desc" rows="2">${this.escape(w.solution_desc ?? '')}</textarea>
                </div>

                <div class="acc-modal__actions">
                    <button type="button" class="acc-btn acc-btn--secondary" data-action="cancel">انصراف</button>
                    <button type="button" class="acc-btn acc-btn--primary" data-action="save">💾 ذخیره</button>
                    ${w.status !== 'closed' ? '<button type="button" class="acc-btn acc-btn--success" data-action="complete">✅ تکمیل و بستن</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(); });

        // افزودن ردیف
        let itemIdx = items.length;
        ov.querySelector("#wo-add-item").addEventListener("click", () => {
            const div = document.createElement("div");
            div.innerHTML = this._renderItemRow({}, itemIdx++);
            ov.querySelector("#wo-items").appendChild(div.firstElementChild);
        });

        const collect = () => {
            const fd = new FormData(ov.querySelector("#wo-form"));
            const body = Object.fromEntries(fd.entries());
            body.items = [];
            ov.querySelectorAll(".wo-item").forEach(row => {
                const desc = row.querySelector("[name='item_desc']")?.value;
                const qty  = parseFloat(row.querySelector("[name='item_qty']")?.value ?? 0);
                const cost = parseFloat(row.querySelector("[name='item_cost']")?.value ?? 0);
                if (desc && qty > 0) body.items.push({ description: desc, qty, unit_cost: cost, item_type: 'part' });
            });
            return body;
        };

        ov.querySelector("[data-action=save]").addEventListener("click", async () => {
            try { await this.api.put(`/assets/work-orders/${w.id}`, collect()); close(); this._load(); }
            catch(e) { alert("خطا: " + (e?.message ?? "")); }
        });

        const completeBtn = ov.querySelector("[data-action=complete]");
        if (completeBtn) completeBtn.addEventListener("click", async () => {
            await this.api.put(`/assets/work-orders/${w.id}`, collect());
            const body = collect();
            try {
                await this.api.post(`/assets/work-orders/${w.id}/complete`, {
                    solution_desc: body.solution_desc,
                    labor_cost: body.labor_cost,
                });
                close(); this._load();
                alert("✅ درخواست تعمیر تکمیل شد");
            } catch(e) { alert("خطا: " + (e?.message ?? "")); }
        });
    }

    _renderItemRow(i, idx) {
        return `
        <div class="wo-item" style="display:grid;grid-template-columns:2fr 1fr 1fr auto;gap:6px;margin-bottom:4px;">
            <input name="item_desc" placeholder="شرح قطعه/کار" value="${this.escape(i.description ?? '')}" class="acc-input">
            <input name="item_qty"  type="number" placeholder="تعداد" value="${i.qty ?? 1}" class="acc-input">
            <input name="item_cost" type="number" placeholder="قیمت واحد" value="${i.unit_cost ?? 0}" class="acc-input">
            <button type="button" class="acc-btn acc-btn--xs gis-btn--danger" onclick="this.parentElement.remove()">✕</button>
        </div>`;
    }

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