/**
 * TechnicianQueueChatSection.js — پایه مشترک صف کار + چت مشتری (کارشناس میدانی)
 */
import SectionBase from "../accounting/SectionBase.js";

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

export default class TechnicianQueueChatSection extends SectionBase {

    constructor(props) {
        super(props);
        this._rows = [];
        this._active = null;
        this._lastMsgId = 0;
        this._pollTimer = null;
    }

    /** عنوان نوار ابزار — در زیرکلاس‌ها قابل تغییر */
    getTitle() {
        return "🔧 صف کار من";
    }

    /** بنر راهنما بالای صفحه — در چت override می‌شود */
    getHeaderHtml() {
        return "";
    }

    async template() {
        return `
        <div class="acc-section-wrap">
            ${this.getHeaderHtml()}
            <div class="acc-toolbar">
                <h2 class="acc-section-title">${this.getTitle()}</h2>
                <button class="acc-btn acc-btn--secondary" data-ref="refreshBtn">🔄</button>
            </div>
            <div class="chat-support-layout" style="display:grid;grid-template-columns:minmax(220px,1fr) 1.4fr;gap:12px;min-height:460px;">
                <aside data-ref="queue" style="overflow-y:auto;max-height:520px;"><div class="acc-loading">⏳</div></aside>
                <div data-ref="chatPanel" class="acc-card" style="padding:12px;display:flex;flex-direction:column;min-height:420px;">
                    <div class="chat-empty-state" style="flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;color:#94a3b8;text-align:center;padding:24px;">
                        <div style="font-size:40px;margin-bottom:8px;">💬</div>
                        <div>یک پرونده را از لیست انتخاب کنید</div>
                        <small style="margin-top:6px;">پاسخ شما در همان چت ویجت مشتری نمایش داده می‌شود</small>
                    </div>
                </div>
            </div>
        </div>`;
    }

    async afterRender() {
        await this._load();
        this.on(this.ref("refreshBtn"), "click", () => this._load());
        this.listen("chat:technician:openRoom", async ({ conversationId, requestId }) => {
            await this._load();
            let row = null;
            if (requestId) row = this._rows.find(r => +r.id === +requestId);
            if (!row && conversationId) row = this._rows.find(r => +r.conversation_id === +conversationId);
            if (row) await this._openChat(row);
        });
        this._pollTimer = setInterval(() => {
            if (this._active?.conversation_id) this._loadMessages();
        }, 5000);
    }

    async _load() {
        this.ref("queue").innerHTML = `<div class="acc-loading">⏳</div>`;
        try {
            const res = await this.api.get("service/technician/my-queue");
            this._rows = res?.data ?? [];
            this._renderQueue();
        } catch (e) {
            this.ref("queue").innerHTML = `<div class="acc-error">❌ ${this.escape(e.message)}</div>`;
        }
    }

    _renderQueue() {
        if (!this._rows.length) {
            this.ref("queue").innerHTML = `
                <div class="acc-empty" style="padding:16px;text-align:center;">
                    <div style="font-size:32px;margin-bottom:8px;">📭</div>
                    <div>درخواست تخصیص‌یافته‌ای ندارید</div>
                    <small style="color:#94a3b8;display:block;margin-top:8px;">پس از Dispatch توسط کارشناس ارشد، پرونده اینجا ظاهر می‌شود</small>
                </div>`;
            return;
        }
        this.ref("queue").innerHTML = this._rows.map(r => {
            const st = STATUS[r.status] ?? { label: r.status, color: "#64748b" };
            const active = this._active?.id == r.id;
            const hasChat = !!r.conversation_id;
            const urgent = r.priority === "urgent";
            return `
            <div class="chat-room-item ${active ? "active" : ""}" data-id="${r.id}"
                 style="cursor:pointer;margin-bottom:8px;padding:12px;border-radius:10px;border:2px solid ${active ? "#3b82f6" : urgent ? "#fecaca" : "#e2e8f0"};background:${active ? "#eff6ff" : urgent ? "#fff1f2" : "#fff"};">
                <div style="display:flex;justify-content:space-between;align-items:center;">
                    <span style="font-family:monospace;font-weight:700;color:#1d4ed8;font-size:14px;">${this.escape(r.tracking_code)}</span>
                    ${urgent ? `<span style="font-size:10px;background:#fef2f2;color:#dc2626;padding:2px 6px;border-radius:6px;">فوری</span>` : ""}
                    ${hasChat ? `<span style="font-size:10px;background:#dcfce7;color:#166534;padding:2px 6px;border-radius:6px;">💬</span>` : ""}
                </div>
                <div style="font-size:13px;font-weight:600;margin-top:4px;">${this.escape(r.customer_name)}</div>
                <div style="font-size:11px;color:#64748b;">${this.escape(r.service_type_label)} · ${this.escape(r.site_label || "—")}</div>
                ${r.dispatch_notes ? `<div style="font-size:10px;background:#fff7ed;color:#c2410c;padding:6px;border-radius:6px;margin-top:6px;">📋 ${this.escape(r.dispatch_notes)}</div>` : ""}
                ${r.phone ? `<div style="font-size:11px;color:#166534;margin-top:2px;" dir="ltr">📱 ${this.escape(r.phone)}</div>` : ""}
                <div style="display:flex;gap:6px;margin-top:8px;flex-wrap:wrap;">
                    <button type="button" class="acc-btn acc-btn--xs acc-btn--primary" data-srd="${r.id}">📄 SRD</button>
                    ${["site_visit", "troubleshooting"].includes(r.service_type) ? `<button type="button" class="acc-btn acc-btn--xs" data-convert="${r.id}">🔧 پیش‌فاکتور</button>` : ""}
                </div>
                <span style="display:inline-block;margin-top:6px;background:${st.color}1a;color:${st.color};padding:2px 8px;border-radius:10px;font-size:10px;font-weight:700;">${st.label}</span>
            </div>`;
        }).join("");

        this.ref("queue").querySelectorAll("[data-id]").forEach(el => {
            el.addEventListener("click", (e) => {
                if (e.target.closest("[data-srd],[data-convert]")) return;
                const row = this._rows.find(r => r.id == el.dataset.id);
                if (row) this._openChat(row);
            });
        });
        this.ref("queue").querySelectorAll("[data-srd]").forEach(btn => {
            btn.addEventListener("click", async (e) => {
                e.stopPropagation();
                await this._openOrCreateReport(+btn.dataset.srd);
            });
        });
        this.ref("queue").querySelectorAll("[data-convert]").forEach(btn => {
            btn.addEventListener("click", async (e) => {
                e.stopPropagation();
                await this._convertToRepair(+btn.dataset.convert);
            });
        });
    }

    async _openOrCreateReport(requestId) {
        const row = this._rows.find(r => r.id === requestId);
        try {
            let reportId = row?.draft_report_id;
            if (!reportId) {
                const res = await this.api.post("service/reports", { request_id: requestId });
                reportId = res?.data?.id;
            }
            if (reportId) this.eventBus?.emit("service:open-report", { id: reportId });
        } catch (e) { alert(e.message); }
    }

    async _convertToRepair(requestId) {
        const row = this._rows.find(r => r.id === requestId);
        const est = prompt("مبلغ پیش‌فاکتور تعمیر (ریال):", "0");
        if (est === null) return;
        try {
            let reportId = row?.draft_report_id;
            if (!reportId) {
                const cr = await this.api.post("service/reports", { request_id: requestId });
                reportId = cr?.data?.id;
            }
            await this.api.post(`service/reports/${reportId}/convert-repair-quote`, { estimate: parseFloat(est) || 0 });
            this.eventBus?.emit("service:open-report", { id: reportId });
        } catch (e) { alert(e.message); }
    }

    async _openChat(row) {
        this._active = row;
        this._lastMsgId = 0;
        this._renderQueue();

        const panel = this.ref("chatPanel");
        if (!row.conversation_id) {
            panel.innerHTML = `<div class="acc-empty">این درخواست هنوز گفتگوی چت ندارد</div>`;
            return;
        }

        const st = STATUS[row.status] ?? { label: row.status, color: "#64748b" };
        panel.innerHTML = `
            <div style="border-bottom:1px solid #e2e8f0;padding-bottom:10px;margin-bottom:10px;">
                <div style="display:flex;flex-wrap:wrap;gap:8px;align-items:center;">
                    <strong style="font-size:15px;">${this.escape(row.customer_name)}</strong>
                    <span style="font-family:monospace;color:#1d4ed8;background:#dbeafe;padding:2px 8px;border-radius:6px;font-weight:700;">${this.escape(row.tracking_code)}</span>
                    <span style="font-size:11px;background:${st.color}1a;color:${st.color};padding:2px 8px;border-radius:8px;">${st.label}</span>
                </div>
                <div style="font-size:12px;color:#64748b;margin-top:4px;">
                    ${row.phone ? `<span dir="ltr">📱 ${this.escape(row.phone)}</span> · ` : ""}
                    ${this.escape(row.site_label || "")}
                </div>
                ${row.dispatch_notes ? `<div style="background:#fff7ed;border:1px solid #fed7aa;padding:8px;border-radius:8px;font-size:11px;color:#c2410c;margin-top:8px;">👨‍💼 دستور ارشد: ${this.escape(row.dispatch_notes)}</div>` : ""}
                <div style="display:flex;gap:8px;margin-top:8px;flex-wrap:wrap;">
                    <button type="button" class="acc-btn acc-btn--xs acc-btn--primary" data-ref="srdBtn">📄 گزارش SRD</button>
                    ${["site_visit", "troubleshooting"].includes(row.service_type) ? `<button type="button" class="acc-btn acc-btn--xs" data-ref="convertBtn">🔧 پیش‌فاکتور تعمیر</button>` : ""}
                </div>
                ${row.status !== "in_progress" ? `<button class="acc-btn acc-btn--xs acc-btn--primary" data-ref="statusBtn" style="margin-top:8px;">▶ شروع کار میدانی</button>` : ""}
            </div>
            <div class="chat-messages" data-ref="messages" style="flex:1;overflow-y:auto;min-height:240px;max-height:360px;background:#f8fafc;border-radius:8px;padding:8px;"></div>
            <div class="chat-input-area" style="display:flex;gap:8px;margin-top:10px;align-items:flex-end;">
                <textarea class="chat-textarea acc-input" data-ref="replyInput" placeholder="پاسخ به مشتری در ویجت..." rows="2" style="flex:1;resize:vertical;"></textarea>
                <button class="acc-btn acc-btn--primary" data-ref="sendBtn">ارسال ➤</button>
            </div>`;
        this._bindRefs();
        this.on(this.ref("sendBtn"), "click", () => this._sendReply());
        this.on(this.ref("replyInput"), "keydown", e => {
            if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); this._sendReply(); }
        });
        this.ref("statusBtn") && this.on(this.ref("statusBtn"), "click", async () => {
            try {
                await this.api.put(`service/requests/${row.id}`, { status: "in_progress" });
                await this._load();
                const updated = this._rows.find(r => r.id == row.id);
                if (updated) await this._openChat(updated);
            } catch (e) { alert(e.message); }
        });
        this.ref("srdBtn") && this.on(this.ref("srdBtn"), "click", () => this._openOrCreateReport(row.id));
        this.ref("convertBtn") && this.on(this.ref("convertBtn"), "click", () => this._convertToRepair(row.id));
        await this._loadMessages(true);
    }

    async _loadMessages(full = false) {
        if (!this._active?.conversation_id) return;
        try {
            const res = await this.api.get(`chat/support/rooms/${this._active.conversation_id}`, {
                last_id: full ? 0 : this._lastMsgId,
            });
            const msgs = res?.data?.messages ?? [];
            const container = this.ref("messages");
            if (!container) return;
            if (full) {
                container.innerHTML = "";
                this._lastMsgId = 0;
            }
            msgs.forEach(m => {
                if (+m.id > this._lastMsgId) {
                    this._lastMsgId = +m.id;
                    this._appendMsg(container, m);
                }
            });
            container.scrollTop = container.scrollHeight;
        } catch {}
    }

    _appendMsg(container, m) {
        const isAgent  = m.sender_type === "agent" || m.sender_type === "user";
        const isSystem = m.sender_type === "system";
        const time = new Date(m.created_at).toLocaleTimeString("fa-IR", { hour: "2-digit", minute: "2-digit" });
        const div = document.createElement("div");
        if (isSystem) {
            div.className = "chat-msg chat-msg--system";
            div.innerHTML = `<span style="font-size:11px;color:#94a3b8;">${this.escape(m.body || m.message)}</span>`;
        } else {
            div.className = `chat-msg ${isAgent ? "chat-msg--out" : "chat-msg--in"}`;
            div.innerHTML = `<div class="chat-bubble">${this.escape(m.body || m.message)}<span class="chat-time">${time}</span></div>`;
        }
        container.appendChild(div);
    }

    async _sendReply() {
        const inp = this.ref("replyInput");
        const body = inp?.value?.trim();
        if (!body || !this._active?.conversation_id) return;
        inp.value = "";
        try {
            await this.api.post(`chat/support/rooms/${this._active.conversation_id}/reply`, { body });
            await this._loadMessages();
        } catch (e) { alert(e.message); }
    }

    destroy() {
        clearInterval(this._pollTimer);
        super.destroy();
    }
}
