import BaseView from "../core/BaseView.js";
import { viewRegistry } from "../core/registries.js";

export default class DashboardView extends BaseView {

    constructor(options = {}) {
        super(options);

        this.api = options.api;
        this.constructor.title = "اطلاعات کاربری";

        this.data = null;
        this.user = null;
        this.loading = false;
    }

    async render(container) {
        await super.render(container);
        await this.loadData();
        return this;
    }

    async template() {
        return `

<style>

.acc-dashboard{
max-width:1200px;
margin:auto;
}

/* tabs */

.acc-tabs{
display:flex;
gap:6px;
border-bottom:1px solid #e5e7eb;
margin-bottom:16px;
}

.acc-tab{
padding:8px 14px;
font-size:13px;
cursor:pointer;
border-radius:6px 6px 0 0;
background:#f3f4f6;
}

.acc-tab.active{
background:#fff;
border:1px solid #e5e7eb;
border-bottom:none;
font-weight:600;
}

.acc-tab-panel{
display:none;
}

.acc-tab-panel.active{
display:block;
}

/* profile */

.acc-profile-card{
background:#fff;
border-radius:12px;
border:1px solid #e5e7eb;
padding:1.5rem;
box-shadow:0 4px 10px rgba(0,0,0,0.05);
}

.acc-profile-header{
display:flex;
align-items:center;
gap:12px;
margin-bottom:16px;
}

.acc-profile-avatar{
width:48px;
height:48px;
border-radius:50%;
background:#3b82f6;
color:#fff;
display:flex;
align-items:center;
justify-content:center;
font-weight:700;
font-size:18px;
}

.acc-profile-name{
font-weight:700;
font-size:15px;
}

.acc-profile-username{
font-size:12px;
color:#6b7280;
}

.acc-profile-body{
display:flex;
flex-direction:column;
gap:10px;
}

.acc-profile-row{
display:flex;
justify-content:space-between;
font-size:13px;
padding:6px 0;
border-bottom:1px dashed #eee;
}

/* permissions */

.acc-permission-accordion{
display:flex;
flex-direction:column;
gap:8px;
}

.acc-permission-item{
border:1px solid #e5e7eb;
border-radius:8px;
background:#fff;
overflow:hidden;
}

.acc-permission-header{
padding:10px 14px;
display:flex;
justify-content:space-between;
cursor:pointer;
background:#f9fafb;
font-weight:600;
font-size:13px;
}

.acc-permission-body{
display:none;
padding:12px 14px;
}

.acc-permission-item.open .acc-permission-body{
display:block;
}

.acc-permission-row{
display:flex;
justify-content:space-between;
padding:6px 0;
font-size:12px;
}

.acc-perm-badge{
background:#eff6ff;
color:#1d4ed8;
padding:2px 6px;
border-radius:4px;
font-size:11px;
margin-left:4px;
}

</style>

<div class="acc-dashboard">

<div class="view-header">
<div>
<h2 class="fw-bold mb-1">داشبورد کاربری</h2>
</div>

<button class="btn btn-outline-secondary btn-sm" data-ref="refreshBtn">
بروزرسانی
</button>
</div>

<div data-ref="alertBox"></div>

<!-- tabs -->

<div class="acc-tabs">

<div class="acc-tab active" data-tab="profile">
پروفایل
</div>

<div class="acc-tab" data-tab="access">
دسترسی‌ها
</div>

<div class="acc-tab" data-tab="future">
تب آینده
</div>

</div>

<!-- tab profile -->

<div class="acc-tab-panel active" data-panel="profile">

<div data-ref="profileSection">
${this.blockSkeleton(4)}
</div>

</div>

<!-- tab access -->

<div class="acc-tab-panel" data-panel="access">

<div data-ref="accessSection">
${this.blockSkeleton(6)}
</div>

</div>

<!-- future tab -->

<div class="acc-tab-panel" data-panel="future">

<div class="text-muted">
در این قسمت می‌توانید تب‌های جدید اضافه کنید
</div>

</div>

</div>
`;
    }

    blockSkeleton(lines = 4) {
        return `
<div class="placeholder-glow">
${Array.from({ length: lines }).map(() =>
            `<div class="placeholder col-12 mb-2" style="height:16px;"></div>`
        ).join("")}
</div>
`;
    }

    async afterRender() {

        const refreshBtn = this.ref("refreshBtn");

        if (refreshBtn) {
            this.on(refreshBtn, "click", () => this.loadData(true));
        }

        /* tabs */

        this.el.querySelectorAll(".acc-tab").forEach(tab => {
            tab.addEventListener("click", () => {

                this.el.querySelectorAll(".acc-tab").forEach(t => t.classList.remove("active"));
                this.el.querySelectorAll(".acc-tab-panel").forEach(p => p.classList.remove("active"));

                tab.classList.add("active");

                const name = tab.dataset.tab;

                this.el.querySelector('[data-panel="' + name + '"]').classList.add("active");

            });
        });

        /* accordion */

        this.el.addEventListener("click", (e) => {

            const header = e.target.closest(".acc-permission-header");

            if (!header) return;

            const item = header.parentElement;

            item.classList.toggle("open");

        });

    }

    async loadData(force = false) {

        if (this.loading && !force) return;

        this.loading = true;

        const alertBox = this.ref("alertBox");

        if (alertBox) alertBox.innerHTML = "";

        try {

            const data = await this.api.get("/dashboard");

            this.data = data;

            const authUser = this.store?.get?.("auth")?.user || null;

            this.user = data.user || authUser || null;

            this.renderProfile(this.user);

            this.renderAccess(data.my_access || []);

        } catch (err) {

            console.error(err);

            if (alertBox) {
                alertBox.innerHTML = `
<div class="alert alert-danger">
خطا در بارگذاری اطلاعات داشبورد
</div>
`;
            }

        } finally {
            this.loading = false;
        }

    }

    renderProfile(user) {

        const el = this.ref("profileSection");

        if (!el) return;

        if (!user) {
            el.innerHTML = `<div class="text-muted">کاربر یافت نشد</div>`;
            return;
        }

        const role = user.accj_role || null;

        const roleTitle =
            role ? (role.name || role.code || "نقش") : "بدون نقش";

        const initials = (user.username || "U").substring(0, 2).toUpperCase();

        el.innerHTML = `

<div class="acc-profile-card">

<div class="acc-profile-header">

<div class="acc-profile-avatar">${this.escape(initials)}</div>

<div>
<div class="acc-profile-name">
${this.escape(user.name || user.display_name || "کاربر")}
</div>

<div class="acc-profile-username">
${this.escape(user.username || "-")}
</div>
</div>

</div>

<div class="acc-profile-body">

<div class="acc-profile-row">
<span>ایمیل</span>
<strong>${this.escape(user.email || "-")}</strong>
</div>

<div class="acc-profile-row">
<span>نقش</span>
<strong>${this.escape(roleTitle)}</strong>
</div>

</div>

</div>

`;
    }

    renderAccess(access) {

        const el = this.ref("accessSection");

        if (!el) return;

        if (!access.length) {
            el.innerHTML = `<div class="text-muted">هیچ دسترسی ثبت نشده است</div>`;
            return;
        }

        const grouped = {};

        access.forEach(item => {
            const module = item.module || item.code || "module";
            if (!grouped[module]) grouped[module] = [];
            grouped[module].push(item);
        });

        el.innerHTML = `

<div class="acc-permission-accordion">

${Object.entries(grouped).map(([module, items]) => `

<div class="acc-permission-item">

<div class="acc-permission-header">
<span>${this.escape(module)}</span>
<span>▾</span>
</div>

<div class="acc-permission-body">

${items.map(i => this.renderPermissionRow(i)).join("")}

</div>

</div>

`).join("")}

</div>

`;
    }

    renderPermissionRow(item) {

        const perms = item.permissions || item.actions || [];

        const title =
            item.menu_title ||
            item.name ||
            item.code ||
            "آیتم";

        return `

<div class="acc-permission-row">

<span>${this.escape(title)}</span>

<div>
${perms.map(p => `
<span class="acc-perm-badge">
${p}
</span>
`).join("")}
</div>

</div>

`;
    }

    escape(str) {

        if (!str) return "";

        return String(str)
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;");

    }

}

viewRegistry.registerByTabKey("dashboard", DashboardView);
