/**
 * ServiceDevicesSection.js — پرونده دستگاه‌ها + نمودار هزینه
 */
import SectionBase from "../../accounting/SectionBase.js";

export default class ServiceDevicesSection 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;">
                    <input data-ref="search" class="acc-input" placeholder="🔍 سریال / برند / موضع" style="width:220px;">
                    <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() {
        await this._load();
        this.on(this.ref("refreshBtn"), "click", () => this._load());
        this.on(this.ref("addBtn"), "click", () => this._openForm());
        this.on(this.ref("search"), "input", () => {
            clearTimeout(this._t);
            this._t = setTimeout(() => this._load(), 300);
        });
    }

    async _load() {
        const q = this.ref("search")?.value?.trim();
        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳</div>`;
        try {
            const res = await this.api.get("service/devices", q ? { search: q } : {});
            this._rows = res?.data ?? [];
            this._render();
        } catch (e) {
            this.ref("wrap").innerHTML = `<div class="acc-error">❌ ${this.escape(e.message)}</div>`;
        }
    }

    _render() {
        if (!this._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>
            </tr></thead>
            <tbody>
            ${this._rows.map(d => `<tr>
                <td>${this.escape(d.site_label || "—")}</td>
                <td>${this.escape(d.device_type || "—")}</td>
                <td>${this.escape(d.brand)} ${this.escape(d.model)}</td>
                <td dir="ltr"><code>${this.escape(d.serial_no)}</code></td>
                <td>${this.escape(d.customer_name)}</td>
                <td>${Number(d.estimated_value || 0).toLocaleString("fa-IR")}</td>
                <td style="white-space:nowrap;">
                    <button class="acc-btn acc-btn--sm" data-chart="${d.id}">📊 هزینه</button>
                    <button class="acc-btn acc-btn--sm" data-timeline="${d.id}">📈 سوابق</button>
                </td>
            </tr>`).join("")}
            </tbody>
        </table>`;

        this.ref("wrap").querySelectorAll("[data-timeline]").forEach(btn => {
            btn.addEventListener("click", () => this._timeline(+btn.dataset.timeline));
        });
        this.ref("wrap").querySelectorAll("[data-chart]").forEach(btn => {
            btn.addEventListener("click", () => this._costChart(+btn.dataset.chart));
        });
    }

    _openModal(title, bodyHtml) {
        const modal = document.createElement("div");
        modal.className = "acc-modal";
        modal.innerHTML = `
        <div class="acc-modal__box" style="max-width:560px;">
            <div class="acc-modal__header">
                <h3>${title}</h3>
                <button class="acc-modal__close">✕</button>
            </div>
            <div style="padding:16px;">${bodyHtml}</div>
        </div>`;
        document.body.appendChild(modal);
        const close = () => modal.remove();
        modal.querySelector(".acc-modal__close").addEventListener("click", close);
        modal.addEventListener("click", e => { if (e.target === modal) close(); });
        return modal;
    }

    async _timeline(id) {
        try {
            const res = await this.api.get(`service/devices/${id}/timeline`);
            const d = res?.data ?? {};
            const reqs = (d.requests || []).map(r =>
                `<li>📋 <b>${this.escape(r.tracking_code)}</b> — ${this.escape(r.service_type)} <small>${(r.created_at || "").slice(0, 10)}</small></li>`
            ).join("") || "<li>—</li>";
            const reps = (d.reports || []).map(r =>
                `<li>📄 <b>${this.escape(r.report_no)}</b> — ${Number(r.total || 0).toLocaleString("fa-IR")} <small>${(r.created_at || "").slice(0, 10)}</small></li>`
            ).join("") || "<li>—</li>";
            this._openModal("📈 سوابق دستگاه", `
                <p><b>درخواست‌ها</b></p><ul style="margin:0 0 16px;padding-right:20px;">${reqs}</ul>
                <p><b>گزارش‌ها</b></p><ul style="margin:0;padding-right:20px;">${reps}</ul>`);
        } catch (e) {
            alert(e.message);
        }
    }

    async _costChart(id) {
        try {
            const res = await this.api.get(`service/devices/${id}/cost-chart`);
            const d = res?.data ?? {};
            const monthly = d.monthly || [];
            const max = Math.max(...monthly.map(m => Number(m.total || 0)), 1);
            const bars = monthly.map(m => {
                const h = Math.round((Number(m.total || 0) / max) * 120);
                return `<div style="flex:1;text-align:center;min-width:36px;">
                    <div style="height:120px;display:flex;align-items:flex-end;justify-content:center;">
                        <div style="width:28px;height:${h}px;background:#3b82f6;border-radius:4px 4px 0 0;" title="${m.total}"></div>
                    </div>
                    <small style="font-size:10px;color:#64748b;">${this.escape(m.month || "")}</small>
                </div>`;
            }).join("") || `<div class="acc-empty">داده‌ای برای نمودار نیست</div>`;

            const warn = d.replace_suggested
                ? `<div style="background:#fef3c7;border:1px solid #f59e0b;border-radius:8px;padding:10px;margin-bottom:12px;font-size:13px;">⚠️ ${this.escape(d.replace_message || "")}</div>`
                : "";

            this._openModal("📊 نمودار هزینه تعمیرات", `
                ${warn}
                <div style="display:flex;gap:12px;margin-bottom:16px;">
                    <div style="flex:1;background:#f8fafc;padding:12px;border-radius:8px;">
                        <div style="font-size:11px;color:#64748b;">مجموع هزینه</div>
                        <div style="font-size:20px;font-weight:800;color:#1d4ed8;">${Number(d.lifetime_cost || 0).toLocaleString("fa-IR")}</div>
                    </div>
                    <div style="flex:1;background:#f8fafc;padding:12px;border-radius:8px;">
                        <div style="font-size:11px;color:#64748b;">ارزش تخمینی</div>
                        <div style="font-size:20px;font-weight:800;">${Number(d.estimated_value || 0).toLocaleString("fa-IR")}</div>
                    </div>
                </div>
                <div style="display:flex;gap:4px;align-items:flex-end;overflow-x:auto;padding-bottom:8px;">${bars}</div>`);
        } catch (e) {
            alert(e.message);
        }
    }

    _openForm(row = null) {
        const modal = document.createElement("div");
        modal.className = "acc-modal";
        modal.innerHTML = `
        <div class="acc-modal__box" style="max-width:480px;">
            <div class="acc-modal__header">
                <h3>${row ? "ویرایش" : "➕"} دستگاه</h3>
                <button class="acc-modal__close">✕</button>
            </div>
            <form class="acc-form" style="padding:16px;display:grid;gap:10px;">
                <div class="acc-form-group"><label>موضع / سایت</label>
                    <input name="site_label" class="acc-input" value="${this.escape(row?.site_label ?? "")}"></div>
                <div class="acc-form-group"><label>نام مشتری</label>
                    <input name="customer_name" class="acc-input" value="${this.escape(row?.customer_name ?? "")}"></div>
                <div class="acc-form-group"><label>نوع دستگاه</label>
                    <input name="device_type" class="acc-input" placeholder="چیلر / سردخانه" value="${this.escape(row?.device_type ?? "")}"></div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;">
                    <div class="acc-form-group"><label>برند</label><input name="brand" class="acc-input" value="${this.escape(row?.brand ?? "")}"></div>
                    <div class="acc-form-group"><label>مدل</label><input name="model" class="acc-input" value="${this.escape(row?.model ?? "")}"></div>
                </div>
                <div class="acc-form-group"><label>شماره سریال</label>
                    <input name="serial_no" class="acc-input" dir="ltr" value="${this.escape(row?.serial_no ?? "")}"></div>
                <div class="acc-form-group"><label>ساعت کارکرد</label>
                    <input name="operating_hours" type="number" min="0" class="acc-input" value="${row?.operating_hours ?? 0}"></div>
                <div class="acc-form-group"><label>ارزش تخمینی دستگاه (تومان)</label>
                    <input name="estimated_value" type="number" min="0" class="acc-input" value="${row?.estimated_value ?? 0}"></div>
                <div style="display:flex;gap:8px;justify-content:flex-end;">
                    <button type="button" class="acc-btn acc-btn--secondary" data-cancel>انصراف</button>
                    <button type="submit" class="acc-btn acc-btn--primary">ذخیره</button>
                </div>
            </form>
        </div>`;
        document.body.appendChild(modal);
        const close = () => modal.remove();
        modal.querySelector(".acc-modal__close").addEventListener("click", close);
        modal.querySelector("[data-cancel]").addEventListener("click", close);
        modal.addEventListener("click", e => { if (e.target === modal) close(); });
        modal.querySelector("form").addEventListener("submit", async e => {
            e.preventDefault();
            const fd = Object.fromEntries(new FormData(e.target).entries());
            fd.estimated_value = Number(fd.estimated_value || 0);
            try {
                if (row) await this.api.put(`service/devices/${row.id}`, fd);
                else await this.api.post("service/devices", fd);
                close();
                await this._load();
            } catch (err) {
                alert(err.message);
            }
        });
    }
}
