/**
 * EmployeesSection.js — مدیریت پرسنل
 */
import SectionBase from "../../accounting/SectionBase.js";

export default class EmployeesSection extends SectionBase {

    constructor(props = {}) {
        super(props);
        this._employees   = [];
        this._allComps    = [];  // all active salary components (for assignment modal)
    }

    async template() {
        return `
            <div style="display:flex;gap:10px;margin-bottom:14px;flex-wrap:wrap;align-items:center;">
                <button class="acc-btn acc-btn--primary acc-btn--sm" data-ref="addBtn">+ پرسنل جدید</button>
                <input type="text" data-ref="searchIn" placeholder="جستجو نام / کد..." style="padding:7px 12px;border:1.5px solid #d1d5db;border-radius:8px;font-size:13px;min-width:200px;">
            </div>
            <div class="entity-grid" data-ref="grid"></div>
        `;
    }

    async afterRender() {
        // Pre-load components for the assignment modal
        try {
            const r = await this.api.get("/payroll/components");
            this._allComps = r?.data ?? [];
        } catch { /* non-fatal */ }

        this.on(this.ref("addBtn"),  "click", ()  => this._openForm(null));
        this.on(this.ref("searchIn"),"input", ()  => this._load(this.ref("searchIn").value));
        await this._load();
    }

    async _load(search = "") {
        const grid = this.ref("grid");
        grid.innerHTML = `<div class="acc-loading" style="grid-column:1/-1"><div class="acc-spinner"></div></div>`;
        try {
            const res = await this.api.get("/payroll/employees", search ? { search } : {});
            this._employees = res?.data ?? [];
            this._render(grid);
        } catch {
            grid.innerHTML = `<div class="acc-error" style="grid-column:1/-1">خطا در بارگذاری پرسنل</div>`;
        }
    }

    _render(grid) {
        if (!this._employees.length) {
            grid.innerHTML = `<div class="acc-empty" style="grid-column:1/-1">پرسنلی یافت نشد.</div>`;
            return;
        }
        grid.innerHTML = "";
        this._employees.forEach(e => {
            const card = document.createElement("div");
            card.className = "entity-card";
            card.innerHTML = `
                <div class="entity-card__code">${this.escape(e.emp_code || "")}</div>
                <div class="entity-card__name">${this.escape(e.full_name)}</div>
                <div class="entity-card__meta">
                    ${e.position   ? `💼 ${this.escape(e.position)}<br>` : ""}
                    ${e.department ? `🏢 ${this.escape(e.department)}<br>` : ""}
                    ${e.hire_date  ? `📅 استخدام: ${e.hire_date}<br>` : ""}
                    ${e.national_id ? `🪪 ${this.escape(e.national_id)}` : ""}
                </div>
                <div class="entity-card__actions">
                    <button class="acc-btn acc-btn--secondary acc-btn--sm" data-action="edit">ویرایش</button>
                    <button class="acc-btn acc-btn--sm payroll-comp-btn" data-action="comps">💰 حقوق</button>
                    <button class="acc-btn acc-btn--danger    acc-btn--sm" data-action="del">حذف</button>
                </div>
            `;
            card.querySelector("[data-action='edit']").addEventListener("click",  () => this._openForm(e));
            card.querySelector("[data-action='comps']").addEventListener("click", () => this._openComponents(e));
            card.querySelector("[data-action='del']").addEventListener("click",   () => this._delete(e));
            grid.appendChild(card);
        });
    }

    /* ── Employee form modal ────────────────────────────────────── */

    _openForm(e = null) {
        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
            <div class="acc-modal" style="max-width:520px;">
                <button class="acc-modal__close">✕</button>
                <div class="acc-modal__title">${e ? "ویرایش پرسنل" : "پرسنل جدید"}</div>
                <form>
                    <div class="doc-form-row">
                        <div class="acc-form-group"><label>کد پرسنلی</label><input name="emp_code" value="${this.escape(e?.emp_code || "")}"></div>
                        <div class="acc-form-group"><label>نام و نام خانوادگی *</label><input name="full_name" value="${this.escape(e?.full_name || "")}" required></div>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group"><label>کد ملی</label><input name="national_id" value="${this.escape(e?.national_id || "")}"></div>
                        <div class="acc-form-group"><label>تاریخ استخدام</label><input type="date" name="hire_date" value="${this.escape(e?.hire_date || "")}"></div>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group"><label>سمت / عنوان شغلی</label><input name="position" value="${this.escape(e?.position || "")}"></div>
                        <div class="acc-form-group"><label>واحد / بخش</label><input name="department" value="${this.escape(e?.department || "")}"></div>
                    </div>
                    <div class="acc-form-group"><label>شماره شبا (IBAN)</label><input name="bank_iban" value="${this.escape(e?.bank_iban || "")}" placeholder="IR..."></div>
                    <div class="acc-modal__actions">
                        <button type="button" class="acc-btn acc-btn--secondary" data-action="cancel">انصراف</button>
                        <button type="submit" class="acc-btn acc-btn--primary">${e ? "ذخیره" : "افزودن"}</button>
                    </div>
                </form>
            </div>`;
        document.body.appendChild(ov);
        const close = () => ov.remove();
        ov.querySelector(".acc-modal__close").addEventListener("click", close);
        ov.querySelector("[data-action='cancel']").addEventListener("click", close);
        ov.addEventListener("click", ev => { if (ev.target === ov) close(); });
        ov.querySelector("form").addEventListener("submit", async ev => {
            ev.preventDefault();
            const body = Object.fromEntries(new FormData(ev.target).entries());
            const btn  = ev.target.querySelector("[type='submit']");
            btn.disabled = true; btn.textContent = "در حال ذخیره...";
            try {
                if (e) await this.api.put(`/payroll/employees/${e.id}`, body);
                else   await this.api.post("/payroll/employees", body);
                close(); await this._load();
            } catch (err) {
                alert("خطا: " + (err?.message ?? ""));
                btn.disabled = false; btn.textContent = e ? "ذخیره" : "افزودن";
            }
        });
    }

    /* ── Component assignment modal ─────────────────────────────── */

    async _openComponents(emp) {
        // Load this employee's current assignments
        let current = [];
        try {
            const r = await this.api.get(`/payroll/employees/${emp.id}/components`);
            current = r?.data ?? [];
        } catch { /* start fresh */ }

        // Build a map: component_id → amount
        const amtMap = {};
        current.forEach(c => { amtMap[c.component_id] = c.amount; });

        if (!this._allComps.length) {
            try {
                const r = await this.api.get("/payroll/components");
                this._allComps = r?.data ?? [];
            } catch {}
        }

        const earnings   = this._allComps.filter(c => c.type === "earning");
        const deductions = this._allComps.filter(c => c.type === "deduction");

        const buildRows = (comps) => comps.map(c => {
            const checked = amtMap[c.id] !== undefined;
            const amt     = amtMap[c.id] ?? c.default_value ?? 0;
            const unit    = c.calc_type === "percent_of_base" ? "٪" : "ریال";
            return `
                <tr>
                    <td style="text-align:center;padding:7px 6px;">
                        <input type="checkbox" class="comp-chk" data-comp="${c.id}" ${checked ? "checked" : ""}>
                    </td>
                    <td style="padding:7px 10px;font-weight:600;">${this.escape(c.name)}</td>
                    <td style="padding:7px 10px;font-size:11px;color:#64748b;">${c.calc_type === "fixed" ? "مبلغ ثابت" : "% از پایه"}</td>
                    <td style="padding:7px 6px;">
                        <input type="number" class="comp-amt" data-comp="${c.id}"
                               value="${amt}" min="0" step="any"
                               style="width:120px;padding:5px 8px;border:1.5px solid #e2e8f0;border-radius:6px;font-size:12px;text-align:left;">
                        <span style="font-size:11px;color:#94a3b8;">${unit}</span>
                    </td>
                </tr>`;
        }).join("");

        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
            <div class="acc-modal" style="max-width:560px;">
                <button class="acc-modal__close">✕</button>
                <div class="acc-modal__title">اجزای حقوق: <span style="color:#2563eb;">${this.escape(emp.full_name)}</span></div>
                <form>
                    <p style="font-size:12px;color:#64748b;margin:0 0 12px;">موارد تیک‌دار در محاسبه فیش این پرسنل استفاده می‌شوند.</p>

                    <div style="font-size:12px;font-weight:700;color:#059669;margin-bottom:6px;">✅ درآمدها</div>
                    <table style="width:100%;border-collapse:collapse;margin-bottom:16px;">
                        <thead><tr style="background:#f0fdf4;font-size:12px;">
                            <th style="padding:7px 6px;text-align:right;width:32px;"></th>
                            <th style="padding:7px 10px;text-align:right;">عنوان</th>
                            <th style="padding:7px 10px;text-align:right;">روش</th>
                            <th style="padding:7px 6px;text-align:right;width:160px;">مبلغ / درصد</th>
                        </tr></thead>
                        <tbody>${buildRows(earnings)}</tbody>
                    </table>

                    <div style="font-size:12px;font-weight:700;color:#dc2626;margin-bottom:6px;">🔻 کسورات</div>
                    <table style="width:100%;border-collapse:collapse;">
                        <thead><tr style="background:#fef2f2;font-size:12px;">
                            <th style="padding:7px 6px;text-align:right;width:32px;"></th>
                            <th style="padding:7px 10px;text-align:right;">عنوان</th>
                            <th style="padding:7px 10px;text-align:right;">روش</th>
                            <th style="padding:7px 6px;text-align:right;width:160px;">مبلغ / درصد</th>
                        </tr></thead>
                        <tbody>${buildRows(deductions)}</tbody>
                    </table>

                    <div class="acc-modal__actions" style="margin-top:16px;">
                        <button type="button" class="acc-btn acc-btn--secondary" data-action="cancel">انصراف</button>
                        <button type="submit" class="acc-btn acc-btn--primary">💾 ذخیره اجزای حقوق</button>
                    </div>
                </form>
            </div>`;
        document.body.appendChild(ov);
        const close = () => ov.remove();
        ov.querySelector(".acc-modal__close").addEventListener("click", close);
        ov.querySelector("[data-action='cancel']").addEventListener("click", close);
        ov.addEventListener("click", ev => { if (ev.target === ov) close(); });

        ov.querySelector("form").addEventListener("submit", async ev => {
            ev.preventDefault();
            const components = [];
            ov.querySelectorAll(".comp-chk:checked").forEach(chk => {
                const compId = parseInt(chk.dataset.comp);
                const amt    = parseFloat(ov.querySelector(`.comp-amt[data-comp="${compId}"]`)?.value ?? 0) || 0;
                components.push({ component_id: compId, amount: amt });
            });
            const btn = ev.target.querySelector("[type='submit']");
            btn.disabled = true; btn.textContent = "در حال ذخیره...";
            try {
                await this.api.post(`/payroll/employees/${emp.id}/components`, { components });
                close();
                this._toast(`✅ اجزای حقوق ${emp.full_name} ذخیره شد`);
            } catch (err) {
                alert("خطا: " + (err?.message ?? ""));
                btn.disabled = false; btn.textContent = "💾 ذخیره اجزای حقوق";
            }
        });
    }

    async _delete(e) {
        if (!confirm(`حذف پرسنل «${e.full_name}»؟`)) return;
        try { await this.api.delete(`/payroll/employees/${e.id}`); await this._load(); }
        catch (err) { alert("خطا: " + (err?.message ?? "")); }
    }

    _toast(msg) {
        const t = document.createElement("div");
        t.style.cssText = "position:fixed;bottom:24px;right:24px;background:#059669;color:#fff;padding:12px 20px;border-radius:10px;font-size:13px;font-weight:600;z-index:9999;box-shadow:0 4px 20px rgba(0,0,0,.15);";
        t.textContent = msg;
        document.body.appendChild(t);
        setTimeout(() => t.remove(), 3500);
    }
}
