/**
 * ServiceSeniorSection.js — پنل کارشناس ارشد (مدیریت تیم)
 */
import SectionBase from "../../accounting/SectionBase.js";

export default class ServiceSeniorSection extends SectionBase {

    constructor(props) {
        super(props);
        this._dash = null;
        this._team = [];
        this._users = [];
        this._pending = [];
    }

    async template() {
        return `
        <div class="acc-section-wrap">
            <div class="acc-toolbar">
                <h2 class="acc-section-title">👨‍💼 پنل کارشناس ارشد</h2>
                <button class="acc-btn acc-btn--secondary" data-ref="refreshBtn">🔄</button>
            </div>
            <div data-ref="stats" class="acc-stats-row" style="display:flex;gap:12px;margin-bottom:16px;flex-wrap:wrap;"></div>
            <div class="acc-card" style="margin-bottom:16px;padding:16px;">
                <h3 style="margin:0 0 12px;font-size:14px;">➕ افزودن کارشناس به تیم</h3>
                <div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;">
                    <select class="acc-input" data-ref="userSel" style="min-width:220px;">
                        <option value="">— انتخاب کاربر —</option>
                    </select>
                    <button class="acc-btn acc-btn--primary" data-ref="addBtn">افزودن</button>
                </div>
            </div>
            <div data-ref="pending" style="margin-bottom:16px;"></div>
            <div data-ref="wrap"><div class="acc-loading">⏳</div></div>
        </div>`;
    }

    async afterRender() {
        await this._loadUsers();
        await this._load();
        this.on(this.ref("refreshBtn"), "click", () => this._load());
        this.on(this.ref("addBtn"), "click", () => this._addMember());
    }

    async _loadUsers() {
        try {
            const res = await this.api.get("acl/users");
            this._users = (res?.data ?? []).filter(u => u.user_id);
            const sel = this.ref("userSel");
            if (!sel) return;
            const inTeam = new Set(this._team.map(t => +t.technician_user_id));
            sel.innerHTML = `<option value="">— انتخاب کاربر —</option>` +
                this._users
                    .filter(u => !inTeam.has(+u.user_id))
                    .map(u => `<option value="${u.user_id}">${this.escape(u.display_name || u.user_login)}</option>`)
                    .join("");
        } catch { this._users = []; }
    }

    async _load() {
        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳</div>`;
        if (this.ref("pending")) this.ref("pending").innerHTML = "";
        try {
            const [dash, team, pending] = await Promise.all([
                this.api.get("service/senior/dashboard"),
                this.api.get("service/senior/team"),
                this.api.get("service/reports/pending-review").catch(() => ({ data: [] })),
            ]);
            this._dash = dash?.data ?? {};
            this._team = team?.data ?? [];
            this._pending = pending?.data ?? [];
            this._renderStats();
            this._renderPending();
            this._renderTeam();
            await this._loadUsers();
        } catch (e) {
            this.ref("wrap").innerHTML = `<div class="acc-error">❌ ${this.escape(e.message)}</div>`;
        }
    }

    _renderPending() {
        const el = this.ref("pending");
        if (!el) return;
        if (!this._pending?.length) { el.innerHTML = ""; return; }
        el.innerHTML = `
        <div class="acc-card" style="padding:16px;">
            <h3 style="margin:0 0 12px;font-size:14px;">📝 گزارش‌های در انتظار بازبینی (${this._pending.length})</h3>
            <table class="acc-table" style="font-size:12px;">
                <thead><tr><th>شماره</th><th>مشتری</th><th>مبلغ</th><th>تاریخ</th><th>یادداشت</th><th></th></tr></thead>
                <tbody>
                ${this._pending.map(r => `<tr data-rid="${r.id}">
                    <td><b>${this.escape(r.report_no)}</b></td>
                    <td>${this.escape(r.customer_name)}</td>
                    <td>${Number(r.total || 0).toLocaleString("fa-IR")}</td>
                    <td><small>${(r.finalized_at || "").slice(0, 16)}</small></td>
                    <td><input class="acc-input" data-note style="font-size:11px;width:120px;" placeholder="توضیح"></td>
                    <td style="white-space:nowrap;">
                        <button class="acc-btn acc-btn--sm acc-btn--primary" data-approve>✅</button>
                        <button class="acc-btn acc-btn--sm" data-reject>❌</button>
                    </td>
                </tr>`).join("")}
                </tbody>
            </table>
        </div>`;
        el.querySelectorAll("[data-approve]").forEach(btn => {
            btn.addEventListener("click", async () => {
                const tr = btn.closest("tr");
                await this._review(+tr.dataset.rid, "approved", tr.querySelector("[data-note]")?.value);
            });
        });
        el.querySelectorAll("[data-reject]").forEach(btn => {
            btn.addEventListener("click", async () => {
                const tr = btn.closest("tr");
                await this._review(+tr.dataset.rid, "rejected", tr.querySelector("[data-note]")?.value);
            });
        });
    }

    async _review(id, status, note) {
        try {
            await this.api.post(`service/reports/${id}/senior-review`, { status, note });
            await this._load();
        } catch (e) { alert(e.message); }
    }

    _renderStats() {
        const d = this._dash || {};
        this.ref("stats").innerHTML = [
            { label: "اعضای تیم", val: d.team_size ?? 0, color: "#3b82f6" },
            { label: "درخواست باز", val: d.open ?? 0, color: "#f59e0b" },
            { label: "تخصیص فعال", val: d.assigned ?? 0, color: "#10b981" },
        ].map(s => `
            <div style="background:${s.color}12;border:1px solid ${s.color}33;border-radius:10px;padding:12px 20px;min-width:120px;">
                <div style="font-size:22px;font-weight:700;color:${s.color};">${s.val}</div>
                <div style="font-size:12px;color:#64748b;">${s.label}</div>
            </div>`).join("");
    }

    _renderTeam() {
        if (!this._team.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>
            </tr></thead>
            <tbody>
            ${this._team.map(t => `
                <tr>
                    <td>${this.escape(t.technician_name)}</td>
                    <td dir="ltr">${this.escape(t.technician_email || "—")}</td>
                    <td><span style="color:${t.status === "active" ? "#10b981" : "#94a3b8"};">${t.status === "active" ? "فعال" : "غیرفعال"}</span></td>
                    <td>
                        ${t.status === "active" ? `<button class="acc-btn acc-btn--sm acc-btn--danger" data-rm="${t.technician_user_id}">حذف</button>` : ""}
                    </td>
                </tr>`).join("")}
            </tbody>
        </table>`;

        this.ref("wrap").querySelectorAll("[data-rm]").forEach(btn => {
            btn.addEventListener("click", async () => {
                if (!confirm("این کارشناس از تیم حذف شود؟")) return;
                try {
                    await this.api.delete(`service/senior/team/${btn.dataset.rm}`);
                    await this._load();
                } catch (e) { alert(e.message); }
            });
        });
    }

    async _addMember() {
        const uid = +(this.ref("userSel")?.value || 0);
        if (!uid) { alert("کاربر را انتخاب کنید"); return; }
        try {
            await this.api.post("service/senior/team", { technician_user_id: uid });
            await this._load();
        } catch (e) { alert(e.message); }
    }
}
