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

const STATUS = {
    submitted:   { label: "ثبت شده", color: "#6366f1" },
    assigned:    { label: "تخصیص", color: "#3b82f6" },
    in_progress: { label: "در حال انجام", color: "#f59e0b" },
    completed:   { label: "تکمیل", color: "#059669" },
    cancelled:   { label: "لغو", color: "#64748b" },
};

export default class ServiceRequestsSection 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;flex-wrap:wrap;">
                    <select data-ref="statusFilter" class="acc-input">
                        <option value="">همه وضعیت‌ها</option>
                        ${Object.entries(STATUS).map(([k,v]) => `<option value="${k}">${v.label}</option>`).join("")}
                    </select>
                    <input type="text" data-ref="search" placeholder="🔍 کد / نام / موضع" class="acc-input" style="width:200px;">
                    <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("search"), "input", () => {
            clearTimeout(this._t);
            this._t = setTimeout(() => this._load(), 300);
        });
    }

    async _load() {
        const params = {};
        const st = this.ref("statusFilter")?.value;
        const q  = this.ref("search")?.value?.trim();
        if (st) params.status = st;
        if (q)  params.search = q;

        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res = await this.api.get("service/requests", params);
            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(r => {
                const st = STATUS[r.status] ?? { label: r.status, color: "#64748b" };
                return `<tr>
                    <td><b style="font-family:monospace;color:#1d4ed8;">${this.escape(r.tracking_code)}</b>
                        <br><small>${this.escape(r.request_no)}</small></td>
                    <td><small>${this.escape(r.service_type_label ?? r.service_type)}</small></td>
                    <td>${this.escape(r.customer_name)}<br><small dir="ltr">${this.escape(r.phone)}</small></td>
                    <td><small>${this.escape(r.site_label || "—")}</small></td>
                    <td><span style="background:${st.color}1a;color:${st.color};padding:2px 8px;border-radius:10px;font-size:11px;font-weight:700;">${st.label}</span></td>
                    <td><small>${(r.created_at || "").slice(0, 16)}</small></td>
                    <td>
                        <button class="acc-btn acc-btn--sm" data-action="report" data-id="${r.id}">📄 گزارش</button>
                        <button class="acc-btn acc-btn--sm acc-btn--secondary" data-action="detail" data-id="${r.id}">👁</button>
                    </td>
                </tr>`;
            }).join("")}
            </tbody>
        </table>`;

        this.ref("wrap").querySelectorAll("[data-action=report]").forEach(btn => {
            btn.addEventListener("click", () => this._createReport(+btn.dataset.id));
        });
        this.ref("wrap").querySelectorAll("[data-action=detail]").forEach(btn => {
            btn.addEventListener("click", () => this._showDetail(+btn.dataset.id));
        });
    }

    async _createReport(requestId) {
        try {
            const res = await this.api.post("service/reports", { request_id: requestId });
            const id = res?.data?.id;
            if (id) {
                this.eventBus?.emit?.("service:open-report", { id });
                alert(`گزارش ${res.data.report_no} ایجاد شد — از تب «گزارش فنی» ویرایش کنید.`);
            }
        } catch (e) {
            alert("خطا: " + (e.message || ""));
        }
    }

    async _showDetail(id) {
        try {
            const res = await this.api.get(`service/requests/${id}`);
            const r = res?.data;
            if (!r) return;

            const tl = (r.timeline || []).map(t => `
                <div class="svc-tl-item">
                    <div class="svc-tl-dot"></div>
                    <div>
                        <div class="svc-tl-label">${this.escape(t.label)}</div>
                        <div class="svc-tl-at">${this.escape((t.at || "").slice(0, 16))}${t.total ? ` · ${Number(t.total).toLocaleString("fa-IR")} ت` : ""}</div>
                    </div>
                </div>`).join("");

            const reports = (r.reports || []).map(rp => `
                <div style="margin:6px 0;padding:8px;background:#f0fdf4;border-radius:8px;font-size:12px;">
                    📄 ${this.escape(rp.report_no)} — ${rp.status === "final" ? "نهایی" : "پیش‌نویس"}
                    ${rp.total ? ` · ${Number(rp.total).toLocaleString("fa-IR")} ت` : ""}
                    ${rp.public_url ? `<a href="${this.escape(rp.public_url)}" target="_blank" style="margin-right:8px;">مشاهده گزارش</a>` : ""}
                </div>`).join("");

            const overlay = document.createElement("div");
            overlay.className = "svc-detail-overlay";
            overlay.innerHTML = `
            <div class="svc-detail-modal" dir="rtl">
                <div class="svc-detail-head">
                    <h3>📋 گزارش کامل پرونده</h3>
                    <button class="acc-btn acc-btn--sm" data-close>✕</button>
                </div>
                <div class="svc-detail-body">
                    <div class="svc-detail-grid">
                        <div><b>کد پیگیری</b><br><span style="font-family:monospace;color:#1d4ed8;font-weight:800;">${this.escape(r.tracking_code)}</span></div>
                        <div><b>نوع خدمت</b><br>${this.escape(r.service_type_label)}</div>
                        <div><b>وضعیت</b><br>${this.escape(r.status_label)}</div>
                        <div><b>مشتری</b><br>${this.escape(r.customer_name)}<br><small dir="ltr">${this.escape(r.phone)}</small></div>
                        <div><b>کارشناس</b><br>${this.escape(r.technician_name || "—")}</div>
                        <div><b>زمان‌بندی</b><br>${this.escape((r.scheduled_at || "").slice(0, 16) || "—")}</div>
                    </div>
                    ${r.dispatch_notes ? `<div class="svc-dispatch-note">👨‍💼 دستور ارشد: ${this.escape(r.dispatch_notes)}</div>` : ""}
                    <div><b>موضع:</b> ${this.escape(r.site_label || "—")}</div>
                    <div><b>دستگاه:</b> ${this.escape(r.brand || "")} ${this.escape(r.model || "")} ${this.escape(r.serial_no || "")}</div>
                    <div><b>شرح:</b> ${this.escape(r.complaint_text || "—")}</div>
                    ${reports ? `<div style="margin-top:12px;"><b>گزارش‌های فنی / فاکتور</b>${reports}</div>` : ""}
                    <div style="margin-top:14px;"><b>⏱ تایم‌لاین مراحل</b></div>
                    <div class="svc-timeline">${tl || '<div class="acc-empty">—</div>'}</div>
                </div>
            </div>`;
            document.body.appendChild(overlay);
            overlay.querySelector("[data-close]")?.addEventListener("click", () => overlay.remove());
            overlay.addEventListener("click", e => { if (e.target === overlay) overlay.remove(); });
        } catch (e) {
            alert(e.message);
        }
    }
}
