/**
 * ComponentsSection.js — تعریف اجزای حقوق
 */
import SectionBase from "../../accounting/SectionBase.js";

const TYPE_LABELS = { earning: "درآمد", deduction: "کسورات" };
const CALC_LABELS = { fixed: "مبلغ ثابت", percent_of_base: "% از پایه" };

export default class ComponentsSection extends SectionBase {

    constructor(props = {}) {
        super(props);
        this._components = [];
    }

    async template() {
        return `
            <div style="display:flex;gap:10px;align-items:center;margin-bottom:16px;flex-wrap:wrap;">
                <button class="acc-btn acc-btn--primary acc-btn--sm" data-ref="addBtn">+ جزء حقوقی جدید</button>
                <span style="font-size:12px;color:#94a3b8;" data-ref="countLbl"></span>
            </div>
            <div data-ref="tableWrap"></div>
        `;
    }

    async afterRender() {
        this.on(this.ref("addBtn"), "click", () => this._openForm(null));
        await this._load();
    }

    async _load() {
        const wrap = this.ref("tableWrap");
        wrap.innerHTML = `<div class="acc-loading"><div class="acc-spinner"></div></div>`;
        try {
            const res = await this.api.get("/payroll/components");
            this._components = res?.data ?? [];
            const lbl = this.ref("countLbl");
            if (lbl) lbl.textContent = `${this._components.length} جزء تعریف‌شده`;
            this._render(wrap);
        } catch {
            wrap.innerHTML = `<div class="acc-error">خطا در بارگذاری</div>`;
        }
    }

    _render(wrap) {
        if (!this._components.length) {
            wrap.innerHTML = `<div class="acc-empty">هیچ جزء حقوقی تعریف نشده است.</div>`;
            return;
        }

        const TH = (t, w = "") => `<th style="padding:10px 12px;text-align:right;font-size:12px;font-weight:700;color:#374151;border-bottom:2px solid #e2e8f0;${w ? 'width:' + w : ''}">${t}</th>`;

        wrap.innerHTML = `
            <div style="overflow-x:auto;">
            <table style="width:100%;border-collapse:collapse;font-size:13px;min-width:600px;">
                <thead><tr style="background:#f8fafc;">
                    ${TH("کد", "60px")}
                    ${TH("عنوان")}
                    ${TH("نوع", "90px")}
                    ${TH("روش محاسبه", "120px")}
                    ${TH("مقدار پیش‌فرض", "130px")}
                    ${TH("بیمه‌پذیر", "70px")}
                    ${TH("مالیاتی", "70px")}
                    ${TH("عملیات", "110px")}
                </tr></thead>
                <tbody data-ref="tbody"></tbody>
            </table>
            </div>`;

        // register the new tbody ref
        this.refs["tbody"] = wrap.querySelector("[data-ref='tbody']");
        const tbody = this.refs["tbody"];

        this._components.forEach((c, idx) => {
            const isEarn = c.type === "earning";
            const tr = document.createElement("tr");
            tr.style.background = idx % 2 === 0 ? "#fff" : "#fafbff";
            tr.innerHTML = `
                <td style="padding:9px 12px;font-family:monospace;font-size:11px;color:#94a3b8;">${this.escape(c.code || "")}</td>
                <td style="padding:9px 12px;font-weight:600;color:#1e293b;">${this.escape(c.name)}</td>
                <td style="padding:9px 12px;">
                    <span class="payroll-type-badge ${isEarn ? "payroll-type-badge--earn" : "payroll-type-badge--ded"}">
                        ${isEarn ? "✅" : "🔻"} ${TYPE_LABELS[c.type] ?? c.type}
                    </span>
                </td>
                <td style="padding:9px 12px;font-size:12px;color:#475569;">${CALC_LABELS[c.calc_type] ?? c.calc_type}</td>
                <td style="padding:9px 12px;text-align:left;font-family:monospace;font-weight:600;">
                    ${this._fmt(c.default_value)}${c.calc_type === "percent_of_base" ? "%" : " ﷼"}
                </td>
                <td style="padding:9px 12px;text-align:center;">${+c.is_insurance_base ? "✅" : "—"}</td>
                <td style="padding:9px 12px;text-align:center;">${+c.is_taxable ? "✅" : "—"}</td>
                <td style="padding:9px 8px;text-align:center;">
                    <button class="acc-btn acc-btn--secondary acc-btn--sm" data-action="edit">ویرایش</button>
                    <button class="acc-btn acc-btn--danger    acc-btn--sm" data-action="del">حذف</button>
                </td>
            `;
            tr.querySelector("[data-action='edit']").addEventListener("click", () => this._openForm(c));
            tr.querySelector("[data-action='del']").addEventListener("click",  () => this._delete(c));
            tbody.appendChild(tr);
        });
    }

    /* ── Form modal ────────────────────────────────────────────── */

    _openForm(c = null) {
        const typeOpts = ["earning", "deduction"].map(t =>
            `<option value="${t}" ${c?.type === t ? "selected" : ""}>${TYPE_LABELS[t]}</option>`
        ).join("");
        const calcOpts = Object.entries(CALC_LABELS).map(([v, l]) =>
            `<option value="${v}" ${c?.calc_type === v ? "selected" : ""}>${l}</option>`
        ).join("");

        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
            <div class="acc-modal" style="max-width:480px;">
                <button class="acc-modal__close">✕</button>
                <div class="acc-modal__title">${c ? "ویرایش جزء حقوقی" : "جزء حقوقی جدید"}</div>
                <form>
                    <div class="doc-form-row">
                        <div class="acc-form-group"><label>کد</label><input name="code" value="${this.escape(c?.code || "")}"></div>
                        <div class="acc-form-group"><label>عنوان *</label><input name="name" value="${this.escape(c?.name || "")}" required></div>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group">
                            <label>نوع</label>
                            <select name="type">${typeOpts}</select>
                        </div>
                        <div class="acc-form-group">
                            <label>روش محاسبه</label>
                            <select name="calc_type">${calcOpts}</select>
                        </div>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group"><label>مقدار پیش‌فرض</label><input name="default_value" type="number" step="any" min="0" value="${c?.default_value ?? 0}"></div>
                        <div class="acc-form-group"><label>ترتیب نمایش</label><input name="sort_order" type="number" min="0" value="${c?.sort_order ?? 0}"></div>
                    </div>
                    <div class="doc-form-row" style="gap:20px;align-items:center;padding:8px 0;">
                        <label style="display:flex;align-items:center;gap:8px;font-size:13px;cursor:pointer;">
                            <input type="checkbox" name="is_insurance_base" value="1" ${+c?.is_insurance_base ? "checked" : ""}>
                            مبنای محاسبه بیمه
                        </label>
                        <label style="display:flex;align-items:center;gap:8px;font-size:13px;cursor:pointer;">
                            <input type="checkbox" name="is_taxable" value="1" ${+c?.is_taxable ? "checked" : ""}>
                            مشمول مالیات
                        </label>
                    </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">${c ? "ذخیره" : "افزودن"}</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 fd   = new FormData(ev.target);
            const body = Object.fromEntries(fd.entries());
            // Checkboxes: if unchecked, FormData omits them — default to 0
            body.is_insurance_base = fd.has("is_insurance_base") ? 1 : 0;
            body.is_taxable        = fd.has("is_taxable")        ? 1 : 0;
            const btn = ev.target.querySelector("[type='submit']");
            btn.disabled = true; btn.textContent = "در حال ذخیره...";
            try {
                if (c) await this.api.put(`/payroll/components/${c.id}`, body);
                else   await this.api.post("/payroll/components", body);
                close(); await this._load();
            } catch (err) {
                alert("خطا: " + (err?.message ?? ""));
                btn.disabled = false; btn.textContent = c ? "ذخیره" : "افزودن";
            }
        });
    }

    async _delete(c) {
        if (!confirm(`حذف «${c.name}»؟`)) return;
        try { await this.api.delete(`/payroll/components/${c.id}`); await this._load(); }
        catch (err) { alert("خطا: " + (err?.message ?? "")); }
    }

    _fmt(v) { return new Intl.NumberFormat("fa-IR").format(Math.round(Number(v ?? 0))); }
}
