/**
 * ServiceDispatchSection.js — تخصیص و dispatch کارشناس
 */
import SectionBase from "../../accounting/SectionBase.js";

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

export default class ServiceDispatchSection extends SectionBase {

    constructor(props) {
        super(props);
        this._techs = [];
    }

    async template() {
        return `
        <div class="acc-section-wrap">
            <div class="acc-toolbar">
                <h2 class="acc-section-title">🚐 Dispatch</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>
                    <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 t = await this.api.get("service/technicians");
            this._techs = t?.data ?? [];
        } catch { this._techs = []; }
        await this._load();
        this.on(this.ref("refreshBtn"), "click", () => this._load());
        this.on(this.ref("statusFilter"), "change", () => this._load());
    }

    async _load() {
        const st = this.ref("statusFilter")?.value;
        const params = st ? { status: st } : {};
        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳</div>`;
        try {
            const res = await this.api.get("service/dispatch/queue", 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;
        }
        const techOpts = `<option value="">— کارشناس —</option>` +
            this._techs.map(t => `<option value="${t.id}">${this.escape(t.name)}</option>`).join("");

        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><th>چت</th><th></th>
            </tr></thead>
            <tbody>
            ${this._rows.map(r => {
                const st = STATUS[r.status] ?? { label: r.status, color: "#64748b" };
                const sched = (r.scheduled_at || "").slice(0, 16).replace("T", " ");
                const urgent = r.priority === "urgent";
                const prioBadge = urgent
                    ? `<span style="background:#fef2f2;color:#dc2626;padding:2px 6px;border-radius:8px;font-size:10px;font-weight:700;">فوری</span>`
                    : `<span style="color:#94a3b8;font-size:10px;">عادی</span>`;
                const benefit = r.has_priority_dispatch
                    ? `<span title="جایزه اولویت اعزام" style="margin-right:4px;">🎁</span>` : "";
                return `<tr data-id="${r.id}" style="${urgent ? "background:#fff1f2;" : ""}">
                    <td>${benefit}<b style="font-family:monospace;color:#1d4ed8;">${this.escape(r.tracking_code)}</b></td>
                    <td>${prioBadge}</td>
                    <td><small>${this.escape(r.service_type_label)}</small></td>
                    <td>${this.escape(r.site_label || "—")}</td>
                    <td>${this.escape(r.customer_name)}<br><small dir="ltr">${this.escape(r.phone)}</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><input type="datetime-local" class="acc-input" data-sched style="font-size:11px;width:150px;" value="${sched ? sched.replace(" ", "T") : ""}"></td>
                    <td><select class="acc-input" data-tech style="font-size:11px;min-width:120px;">${techOpts}</select></td>
                    <td><textarea class="acc-input" data-notes placeholder="توضیح ارشد برای کارشناس..." style="font-size:11px;width:140px;min-height:48px;">${this.escape(r.dispatch_notes || "")}</textarea></td>
                    <td>${r.conversation_id ? `<button class="acc-btn acc-btn--sm acc-btn--secondary" data-chat title="باز کردن چت">💬</button>` : "—"}</td>
                    <td><button class="acc-btn acc-btn--sm acc-btn--primary" data-save>💾</button></td>
                </tr>`;
            }).join("")}
            </tbody>
        </table>`;

        this.ref("wrap").querySelectorAll("tr[data-id]").forEach(tr => {
            const id = +tr.dataset.id;
            const row = this._rows.find(r => r.id == id);
            const techSel = tr.querySelector("[data-tech]");
            const schedIn = tr.querySelector("[data-sched]");
            if (row?.assigned_technician_id) techSel.value = row.assigned_technician_id;
            tr.querySelector("[data-chat]")?.addEventListener("click", () => {
                if (!row?.conversation_id) return;
                this.eventBus?.emit("tab:open", { key: "chat" });
                setTimeout(() => {
                    this.eventBus?.emit("chat:support:openRoom", { conversationId: +row.conversation_id });
                    this.eventBus?.emit("chat:technician:openRoom", {
                        conversationId: +row.conversation_id,
                        requestId: +row.id,
                    });
                }, 400);
            });
            tr.querySelector("[data-save]").addEventListener("click", async () => {
                const payload = {
                    technician_id: techSel.value ? +techSel.value : 0,
                    scheduled_at: schedIn.value ? schedIn.value.replace("T", " ") : "",
                    dispatch_notes: tr.querySelector("[data-notes]")?.value || "",
                    status: techSel.value ? "assigned" : "submitted",
                };
                try {
                    await this.api.post(`service/requests/${id}/assign`, payload);
                    await this._load();
                } catch (e) { alert(e.message); }
            });
        });
    }
}
