/**
 * AssetsListSection.js — لیست + مدیریت اموال (با LocationPicker)
 */
import SectionBase from "../../accounting/SectionBase.js";
import LocationPicker from "../../gis/components/LocationPicker.js";

const STATUS = {
    active:    { label:'فعال',     color:'#10b981' },
    in_repair: { label:'در تعمیر',  color:'#f59e0b' },
    retired:   { label:'بازنشسته',  color:'#94a3b8' },
    sold:      { label:'فروخته شده',color:'#06b6d4' },
    damaged:   { label:'آسیب‌دیده', color:'#ef4444' },
};

const CONDITION = {
    excellent:'عالی', good:'خوب', fair:'متوسط', poor:'ضعیف', broken:'خراب',
};

export default class AssetsListSection extends SectionBase {

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

    async template() {
        return `
        <div class="acc-section-wrap">
            <div class="acc-toolbar">
                <h2 class="acc-section-title">📦 اموال</h2>
                <div style="display:flex;gap:8px;flex-wrap:wrap;">
                    <input type="text" data-ref="search" placeholder="🔍 جستجو..." class="acc-input" style="width:200px;">
                    <select data-ref="catFilter" class="acc-input"><option value="">همه دسته‌ها</option></select>
                    <select data-ref="statusFilter" class="acc-input">
                        <option value="">همه وضعیت‌ها</option>
                        ${Object.entries(STATUS).map(([k,v]) => `<option value="${k}">${v.label}</option>`).join("")}
                    </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() {
        try {
            const r = await this.api.get("/assets/categories");
            this._cats = r?.data ?? [];
            const sel = this.ref("catFilter");
            this._cats.forEach(c => {
                const o = document.createElement("option");
                o.value = c.id; o.textContent = `${c.icon} ${c.name}`;
                sel.appendChild(o);
            });
        } catch {}
        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("catFilter"),    "change", () => this._load());
        this.on(this.ref("statusFilter"), "change", () => this._load());
    }

    async _load() {
        const params = {};
        const s = this.ref("search")?.value?.trim();
        const c = this.ref("catFilter")?.value;
        const st = this.ref("statusFilter")?.value;
        if (s)  params.search      = s;
        if (c)  params.category_id = c;
        if (st) params.status      = st;

        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res = await this.api.get("/assets", 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(280px,1fr));gap:14px;">
            ${this._rows.map(a => {
                const s = STATUS[a.status] ?? { label:a.status, color:'#64748b' };
                return `
                <div style="border:1px solid #e2e8f0;border-radius:10px;padding:14px;background:#fff;">
                    <div style="display:flex;justify-content:space-between;align-items:start;">
                        <div style="flex:1;">
                            <div style="font-size:20px;">${a.category_icon || '📦'}</div>
                            <div style="font-weight:700;font-size:14px;margin-top:4px;">${this.escape(a.name)}</div>
                            <small style="color:#94a3b8;font-family:monospace;">${this.escape(a.asset_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>
                    <div style="font-size:12px;color:#64748b;margin-top:8px;line-height:1.6;">
                        ${a.brand ? `🏷️ ${this.escape(a.brand)} ${this.escape(a.model || '')}<br>` : ''}
                        ${a.serial_no ? `🔢 <span dir="ltr">${this.escape(a.serial_no)}</span><br>` : ''}
                        ${a.assigned_name ? `👤 ${this.escape(a.assigned_name)}<br>` : ''}
                        ${parseFloat(a.current_value) > 0 ? `💰 ارزش: <b style="color:#059669;">${this._fmt(a.current_value)} ﷼</b>` : ''}
                    </div>
                    <div style="display:flex;gap:4px;margin-top:10px;flex-wrap:wrap;">
                        <button class="acc-btn acc-btn--xs" data-edit="${a.id}">✏️</button>
                        <button class="acc-btn acc-btn--xs" data-loc="${a.id}" data-name="${this.escape(a.name)}" style="background:#dbeafe;color:#1e40af;">📍</button>
                        <button class="acc-btn acc-btn--xs" data-repair="${a.id}" data-name="${this.escape(a.name)}" style="background:#fef3c7;color:#92400e;">🔧 تعمیر</button>
                        <button class="acc-btn acc-btn--xs gis-btn--danger" data-del="${a.id}">🗑️</button>
                    </div>
                </div>`;
            }).join("")}
        </div>`;

        this.ref("wrap").querySelectorAll("[data-edit]").forEach(b =>
            b.addEventListener("click", () => this._openModal(this._rows.find(r => r.id == b.dataset.edit)))
        );
        this.ref("wrap").querySelectorAll("[data-loc]").forEach(b =>
            b.addEventListener("click", () => LocationPicker.openModal({
                api: this.api, entityType: 'asset',
                entityId: parseInt(b.dataset.loc), entityName: b.dataset.name,
            }))
        );
        this.ref("wrap").querySelectorAll("[data-repair]").forEach(b =>
            b.addEventListener("click", () => this._openRepairModal(parseInt(b.dataset.repair), b.dataset.name))
        );
        this.ref("wrap").querySelectorAll("[data-del]").forEach(b =>
            b.addEventListener("click", async () => {
                if (!confirm("بازنشسته کردن این دارایی؟")) return;
                try { await this.api.delete(`/assets/${b.dataset.del}`); this._load(); }
                catch(e) { alert("خطا: " + (e?.message ?? "")); }
            })
        );
    }

    _openModal(a = null) {
        const isEdit = !!a;
        const catOpts = this._cats.map(c =>
            `<option value="${c.id}" ${a?.category_id == c.id ? 'selected' : ''}>${c.icon} ${this.escape(c.name)}</option>`).join("");
        const statusOpts = Object.entries(STATUS).map(([k,v]) =>
            `<option value="${k}" ${a?.status === k ? 'selected' : ''}>${v.label}</option>`).join("");
        const condOpts = Object.entries(CONDITION).map(([k,v]) =>
            `<option value="${k}" ${a?.condition_grade === k ? 'selected' : ''}>${v}</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="asset_code" value="${this.escape(a?.asset_code ?? '')}" placeholder="(خودکار)">
                    </div>
                    <div class="acc-form-group"><label>دسته‌بندی</label>
                        <select name="category_id"><option value="">—</option>${catOpts}</select>
                    </div>
                </div>
                <div class="acc-form-group"><label>نام *</label>
                    <input name="name" required value="${this.escape(a?.name ?? '')}">
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>برند</label><input name="brand" value="${this.escape(a?.brand ?? '')}"></div>
                    <div class="acc-form-group"><label>مدل</label><input name="model" value="${this.escape(a?.model ?? '')}"></div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>شماره سریال</label>
                        <input name="serial_no" value="${this.escape(a?.serial_no ?? '')}" dir="ltr">
                    </div>
                    <div class="acc-form-group"><label>پلاک (خودرو)</label>
                        <input name="plate_no" value="${this.escape(a?.plate_no ?? '')}" dir="ltr">
                    </div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>وضعیت</label><select name="status">${statusOpts}</select></div>
                    <div class="acc-form-group"><label>کیفیت</label><select name="condition_grade">${condOpts}</select></div>
                </div>
                <div class="gis-info-divider">خرید</div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>تاریخ خرید</label>
                        <input name="purchase_date" type="date" value="${a?.purchase_date ?? ''}">
                    </div>
                    <div class="acc-form-group"><label>قیمت خرید (﷼)</label>
                        <input name="purchase_price" type="number" min="0" value="${a?.purchase_price ?? 0}">
                    </div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>ارزش فعلی (﷼)</label>
                        <input name="current_value" type="number" min="0" value="${a?.current_value ?? 0}">
                    </div>
                    <div class="acc-form-group"><label>تاریخ سرویس بعدی</label>
                        <input name="next_service_date" type="date" value="${a?.next_service_date ?? ''}">
                    </div>
                </div>
                <div class="gis-info-divider">گارانتی و بیمه</div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>انقضای گارانتی</label>
                        <input name="warranty_expiry" type="date" value="${a?.warranty_expiry ?? ''}">
                    </div>
                    <div class="acc-form-group"><label>انقضای بیمه</label>
                        <input name="insurance_expiry" type="date" value="${a?.insurance_expiry ?? ''}">
                    </div>
                </div>
                <div class="acc-form-group"><label>مسئول/تحویل‌گیرنده</label>
                    <input name="assigned_name" value="${this.escape(a?.assigned_name ?? '')}">
                </div>
                <div class="acc-form-group"><label>توضیحات</label>
                    <textarea name="description" rows="2">${this.escape(a?.description ?? '')}</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());
            try {
                if (isEdit) await this.api.put(`/assets/${a.id}`, body);
                else        await this.api.post("/assets", body);
                close(); this._load();
            } catch(e) { alert("خطا: " + (e?.message ?? "")); }
        });
    }

    _openRepairModal(assetId, assetName) {
        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:440px;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">🔧 درخواست تعمیر — ${this.escape(assetName)}</div>
            <form>
                <div class="acc-form-group"><label>عنوان مشکل *</label>
                    <input name="title" required placeholder="مثلاً: صدای غیرعادی موتور">
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>نوع</label>
                        <select name="type">
                            <option value="corrective">🔧 اصلاحی (خرابی)</option>
                            <option value="preventive">📅 پیشگیرانه</option>
                            <option value="inspection">🔍 بازرسی</option>
                            <option value="emergency">🚨 اضطراری</option>
                        </select>
                    </div>
                    <div class="acc-form-group"><label>اولویت</label>
                        <select name="priority">
                            <option value="low">پایین</option>
                            <option value="medium" selected>متوسط</option>
                            <option value="high">بالا</option>
                            <option value="urgent">فوری</option>
                        </select>
                    </div>
                </div>
                <div class="acc-form-group"><label>توضیح مشکل</label>
                    <textarea name="problem_desc" rows="3"></textarea>
                </div>
                <div class="acc-form-group"><label>تخصیص به</label>
                    <input name="assigned_name" placeholder="نام تعمیرکار/پیمانکار">
                </div>
                <div class="acc-form-group"><label>تاریخ موعد</label>
                    <input name="due_date" type="date">
                </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());
            body.asset_id = assetId;
            try {
                const res = await this.api.post("/assets/work-orders", body);
                close();
                alert(`✅ درخواست تعمیر ${res?.wo_no} ایجاد شد`);
                this._load();
            } catch(e) { alert("خطا: " + (e?.message ?? "")); }
        });
    }

    _fmt(v) { return new Intl.NumberFormat("fa-IR").format(Math.round(Number(v ?? 0))); }
    escape(s) { return String(s ?? "").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"); }
}
