/**
 * AclUsersSection.js — لیست کاربران + اختصاص نقش
 */
import SectionBase from "../../accounting/SectionBase.js";

export default class AclUsersSection extends SectionBase {

    constructor(p) { super(p); this._roles = []; this._users = []; }

    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 type="text" data-ref="search" placeholder="جستجو کاربر..."
                           class="acc-input" style="width:220px;">
                    <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._loadRoles();
        await this._load();
        this.on(this.ref("refreshBtn"), "click", () => this._load());
        this.on(this.ref("search"),     "input", () => this._filter());
    }

    async _loadRoles() {
        try {
            const r = await this.api.get("/acl/roles");
            this._roles = r?.data ?? [];
        } catch {}
    }

    async _load() {
        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res = await this.api.get("/acl/users");
            this._users = res?.data ?? [];
            this._renderTable(this._users);
        } catch {
            this.ref("wrap").innerHTML = `<div class="acc-error">❌ خطا</div>`;
        }
    }

    _filter() {
        const q = (this.ref("search")?.value ?? "").toLowerCase();
        if (!q) { this._renderTable(this._users); return; }
        this._renderTable(this._users.filter(u =>
            (u.display_name ?? "").toLowerCase().includes(q) ||
            (u.user_login   ?? "").toLowerCase().includes(q) ||
            (u.user_email   ?? "").toLowerCase().includes(q)
        ));
    }

    _renderTable(rows) {
        if (!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>
            </tr></thead>
            <tbody>
            ${rows.map(u => `<tr>
                <td>
                    <div style="font-weight:700;">${this.escape(u.display_name ?? u.user_login)}</div>
                    <small style="color:#94a3b8;">${this.escape(u.user_login)}</small>
                </td>
                <td><small>${this.escape(u.user_email ?? "—")}</small></td>
                <td style="max-width:300px;">
                    ${u.roles_list
                        ? `<small style="color:#475569;">${this.escape(u.roles_list)}</small>`
                        : `<span style="color:#cbd5e1;font-size:11px;">— بدون نقش —</span>`}
                </td>
                <td style="text-align:center;">
                    <span style="background:${u.role_count > 0 ? '#d1fae5' : '#fee2e2'};
                                 color:${u.role_count > 0 ? '#065f46' : '#991b1b'};
                                 padding:2px 8px;border-radius:10px;font-size:11px;font-weight:700;">
                        ${u.role_count}
                    </span>
                </td>
                <td>
                    <button class="acc-btn acc-btn--xs acc-btn--primary" data-uid="${u.user_id}">⚙️ مدیریت نقش‌ها</button>
                </td>
            </tr>`).join("")}
            </tbody>
        </table>`;

        this.ref("wrap").querySelectorAll("[data-uid]").forEach(btn =>
            btn.addEventListener("click", () => this._openRolesModal(parseInt(btn.dataset.uid),
                rows.find(u => u.user_id == btn.dataset.uid)))
        );
    }

    async _openRolesModal(userId, user) {
        let assignments = [];
        try {
            const res = await this.api.get(`/acl/users/${userId}/roles`);
            assignments = res?.data ?? [];
        } catch {}

        const roleOpts = this._roles.map(r =>
            `<option value="${r.id}">${this.escape(r.name)}</option>`).join("");

        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:560px;max-height:90vh;overflow-y:auto;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">⚙️ نقش‌های ${this.escape(user?.display_name ?? '')}</div>

            <!-- نقش‌های فعلی -->
            <div style="margin-bottom:14px;">
                <b style="font-size:13px;">نقش‌های فعلی:</b>
                <div data-ref-inner="assignments" id="acl-assignments-list" style="margin-top:6px;"></div>
            </div>

            <!-- افزودن نقش جدید -->
            <div style="background:#f8fafc;padding:12px;border-radius:8px;">
                <b style="font-size:13px;">➕ افزودن نقش جدید:</b>
                <form id="acl-assign-form" style="display:grid;grid-template-columns:1fr 1fr 1fr auto;gap:6px;margin-top:8px;align-items:end;">
                    <div>
                        <label style="font-size:11px;">نقش *</label>
                        <select name="role_id" required class="acc-input"><option value="">انتخاب...</option>${roleOpts}</select>
                    </div>
                    <div>
                        <label style="font-size:11px;">نوع scope</label>
                        <select name="scope_type" class="acc-input">
                            <option value="global">سراسری</option>
                            <option value="project">پروژه</option>
                            <option value="warehouse">انبار</option>
                            <option value="district">منطقه GIS</option>
                        </select>
                    </div>
                    <div>
                        <label style="font-size:11px;">ID شیء</label>
                        <input name="scope_id" type="number" class="acc-input" placeholder="(اختیاری)">
                    </div>
                    <button type="submit" class="acc-btn acc-btn--primary acc-btn--sm">➕</button>
                </form>
            </div>

            <div class="acc-modal__actions" style="margin-top:14px;">
                <button type="button" class="acc-btn acc-btn--secondary" data-action="close">بستن</button>
            </div>
        </div>`;
        document.body.appendChild(ov);
        const close = () => { ov.remove(); this._load(); };
        ov.querySelector(".acc-modal__close").addEventListener("click", close);
        ov.querySelector("[data-action=close]").addEventListener("click", close);
        ov.addEventListener("click", e => { if (e.target === ov) close(); });

        const renderAssignments = () => {
            const wrap = ov.querySelector("#acl-assignments-list");
            if (!assignments.length) {
                wrap.innerHTML = `<div style="color:#94a3b8;font-size:12px;padding:8px;">— نقشی اختصاص داده نشده —</div>`;
                return;
            }
            wrap.innerHTML = assignments.map(a => `
                <div style="display:flex;justify-content:space-between;align-items:center;padding:6px 10px;background:#fff;border:1px solid #e2e8f0;border-radius:6px;margin-bottom:4px;">
                    <div>
                        <b style="font-size:13px;">${this.escape(a.role_name)}</b>
                        <small style="color:#64748b;margin-right:8px;">
                            ${a.scope_type === 'global' ? '🌐 سراسری' : `${this.escape(a.scope_type)}: ${a.scope_id ?? '—'}`}
                        </small>
                    </div>
                    <button class="acc-btn acc-btn--xs gis-btn--danger" data-del="${a.assignment_id}">🗑️</button>
                </div>
            `).join("");

            wrap.querySelectorAll("[data-del]").forEach(btn =>
                btn.addEventListener("click", async () => {
                    if (!confirm("حذف این نقش از کاربر؟")) return;
                    try {
                        await this.api.delete(`/acl/users/${userId}/roles/${btn.dataset.del}`);
                        assignments = assignments.filter(a => a.assignment_id != btn.dataset.del);
                        renderAssignments();
                    } catch(e) { alert("خطا: " + (e?.message ?? "")); }
                })
            );
        };
        renderAssignments();

        ov.querySelector("#acl-assign-form").addEventListener("submit", async ev => {
            ev.preventDefault();
            const body = Object.fromEntries(new FormData(ev.target).entries());
            if (!body.scope_id) delete body.scope_id;
            try {
                await this.api.post(`/acl/users/${userId}/roles`, body);
                const res = await this.api.get(`/acl/users/${userId}/roles`);
                assignments = res?.data ?? [];
                renderAssignments();
                ev.target.reset();
            } catch(e) { alert("خطا: " + (e?.message ?? "")); }
        });
    }

    escape(s) { return String(s ?? "").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"); }
}
