/**
 * HrEmployeesSection.js — کارمندان + LocationPicker
 */
import SectionBase from "../../accounting/SectionBase.js";
import LocationPicker from "../../gis/components/LocationPicker.js";

const STATUS = {
    active: { label:'فعال', color:'#10b981' },
    inactive: { label:'غیرفعال', color:'#94a3b8' },
    on_leave: { label:'در مرخصی', color:'#f59e0b' },
};

export default class HrEmployeesSection extends SectionBase {

    constructor(p) { super(p); this._depts = []; this._positions = []; }

    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;">
                    <select data-ref="deptFilter" class="acc-input"><option value="">همه بخش‌ها</option></select>
                    <button class="acc-btn acc-btn--primary" data-ref="addBtn">➕ کارمند جدید</button>
                    <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 Promise.all([this._loadDepts(), this._loadPositions()]);
        await this._load();
        this.on(this.ref("refreshBtn"), "click", () => this._load());
        this.on(this.ref("addBtn"),     "click", () => this._openModal());
        this.on(this.ref("search"),     "input", () => { clearTimeout(this._t); this._t = setTimeout(() => this._load(), 300); });
        this.on(this.ref("deptFilter"), "change", () => this._load());
    }

    async _loadDepts() {
        try {
            const r = await this.api.get("/hr/departments");
            this._depts = r?.data ?? [];
            const sel = this.ref("deptFilter");
            this._depts.forEach(d => { const o = document.createElement("option"); o.value = d.id; o.textContent = d.name; sel.appendChild(o); });
        } catch {}
    }
    async _loadPositions() {
        try { const r = await this.api.get("/hr/positions"); this._positions = r?.data ?? []; } catch {}
    }

    async _load() {
        const params = {};
        const s = this.ref("search")?.value?.trim();
        const d = this.ref("deptFilter")?.value;
        if (s) params.search = s;
        if (d) params.department_id = d;

        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res = await this.api.get("/hr/employees", params);
            this._rows = res?.data ?? [];
            this._render();
        } catch { this.ref("wrap").innerHTML = `<div class="acc-error">❌ خطا</div>`; }
    }

    _render() {
        if (!this._rows.length) { this.ref("wrap").innerHTML = `<div class="acc-empty">کارمندی یافت نشد</div>`; return; }
        this.ref("wrap").innerHTML = `
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:12px;padding:4px;">
            ${this._rows.map(e => {
                const s = STATUS[e.status] ?? { label: e.status, color: '#64748b' };
                return `
                <div style="border:1px solid #e2e8f0;border-radius:10px;padding:12px;background:#fff;">
                    <div style="display:flex;justify-content:space-between;align-items:start;">
                        <div style="flex:1;">
                            <div style="font-weight:700;font-size:14px;">👤 ${this.escape(e.full_name)}</div>
                            <small style="color:#94a3b8;font-family:monospace;">${this.escape(e.employee_code)}</small>
                        </div>
                        <span style="background:${s.color}1a;color:${s.color};padding:2px 8px;border-radius:10px;font-size:11px;font-weight:700;">${s.label}</span>
                    </div>
                    ${e.position_title ? `<div style="font-size:12px;color:#475569;margin-top:6px;">💼 ${this.escape(e.position_title)}</div>` : ''}
                    ${e.dept_name     ? `<div style="font-size:12px;color:#64748b;">🏢 ${this.escape(e.dept_name)}</div>` : ''}
                    ${e.mobile        ? `<div style="font-size:12px;color:#64748b;direction:ltr;text-align:right;">📱 ${this.escape(e.mobile)}</div>` : ''}
                    <div style="display:flex;gap:4px;margin-top:10px;">
                        <button class="acc-btn acc-btn--xs" data-edit="${e.id}">✏️ ویرایش</button>
                        <button class="acc-btn acc-btn--xs" data-loc="${e.id}" data-name="${this.escape(e.full_name)}" style="background:#dbeafe;color:#1e40af;">📍 موقعیت‌ها</button>
                    </div>
                </div>`;
            }).join("")}
        </div>`;

        this.ref("wrap").querySelectorAll("[data-edit]").forEach(btn =>
            btn.addEventListener("click", () => this._openModal(this._rows.find(r => r.id == btn.dataset.edit)))
        );
        this.ref("wrap").querySelectorAll("[data-loc]").forEach(btn =>
            btn.addEventListener("click", () => LocationPicker.openModal({
                api: this.api, entityType: 'employee',
                entityId: parseInt(btn.dataset.loc), entityName: btn.dataset.name,
            }))
        );
    }

    _openModal(emp = null) {
        const isEdit = !!emp;
        const deptOpts = `<option value="">—</option>` + this._depts.map(d =>
            `<option value="${d.id}" ${emp?.department_id == d.id ? 'selected' : ''}>${this.escape(d.name)}</option>`).join("");
        const posOpts = `<option value="">—</option>` + this._positions.map(p =>
            `<option value="${p.id}" ${emp?.position_id == p.id ? 'selected' : ''}>${this.escape(p.title)}</option>`).join("");

        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:640px;max-height:92vh;overflow-y:auto;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">${isEdit ? '✏️ ویرایش' : '➕ کارمند جدید'}</div>
            <form>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>کد کارمندی</label>
                        <input name="employee_code" value="${this.escape(emp?.employee_code ?? '')}" placeholder="(خودکار)">
                    </div>
                    <div class="acc-form-group"><label>وضعیت</label>
                        <select name="status">
                            ${Object.entries(STATUS).map(([k,v]) => `<option value="${k}" ${emp?.status===k?'selected':''}>${v.label}</option>`).join("")}
                        </select>
                    </div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>نام *</label>
                        <input name="first_name" required value="${this.escape(emp?.first_name ?? '')}">
                    </div>
                    <div class="acc-form-group"><label>نام خانوادگی *</label>
                        <input name="last_name" required value="${this.escape(emp?.last_name ?? '')}">
                    </div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>کد ملی</label>
                        <input name="national_id" value="${this.escape(emp?.national_id ?? '')}">
                    </div>
                    <div class="acc-form-group"><label>نام پدر</label>
                        <input name="father_name" value="${this.escape(emp?.father_name ?? '')}">
                    </div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>تاریخ تولد</label>
                        <input name="birth_date" type="date" value="${emp?.birth_date ?? ''}">
                    </div>
                    <div class="acc-form-group"><label>جنسیت</label>
                        <select name="gender">
                            <option value="">—</option>
                            <option value="male"   ${emp?.gender==='male'?'selected':''}>مرد</option>
                            <option value="female" ${emp?.gender==='female'?'selected':''}>زن</option>
                        </select>
                    </div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>موبایل</label>
                        <input name="mobile" value="${this.escape(emp?.mobile ?? '')}" dir="ltr">
                    </div>
                    <div class="acc-form-group"><label>ایمیل</label>
                        <input name="email" type="email" value="${this.escape(emp?.email ?? '')}" dir="ltr">
                    </div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>بخش</label>
                        <select name="department_id">${deptOpts}</select>
                    </div>
                    <div class="acc-form-group"><label>سمت</label>
                        <select name="position_id">${posOpts}</select>
                    </div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>تاریخ استخدام</label>
                        <input name="hire_date" type="date" value="${emp?.hire_date ?? ''}">
                    </div>
                    <div class="acc-form-group"><label>نوع همکاری</label>
                        <select name="employment_type">
                            <option value="full_time"  ${emp?.employment_type==='full_time'?'selected':''}>تمام‌وقت</option>
                            <option value="part_time"  ${emp?.employment_type==='part_time'?'selected':''}>پاره‌وقت</option>
                            <option value="contract"   ${emp?.employment_type==='contract'?'selected':''}>قرارداد موقت</option>
                            <option value="freelance"  ${emp?.employment_type==='freelance'?'selected':''}>پروژه‌ای</option>
                        </select>
                    </div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>حقوق پایه (ریال)</label>
                        <input name="base_salary" type="number" value="${emp?.base_salary ?? 0}">
                    </div>
                    <div class="acc-form-group"><label>شماره IBAN</label>
                        <input name="iban" value="${this.escape(emp?.iban ?? '')}" dir="ltr">
                    </div>
                </div>
                <div class="acc-form-group"><label>یادداشت</label>
                    <textarea name="notes" rows="2">${this.escape(emp?.notes ?? '')}</textarea>
                </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">ذخیره</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", e => { if (e.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;
            try {
                if (isEdit) await this.api.put(`/hr/employees/${emp.id}`, body);
                else        await this.api.post("/hr/employees", body);
                close(); this._load();
            } catch(e) { alert("خطا: " + (e?.message ?? "")); btn.disabled = false; }
        });
    }

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