/**
 * ProductsSection.js — مدیریت محصولات و خدمات
 */
import SectionBase from "../../accounting/SectionBase.js";

const PRODUCT_TYPES = [
    { value: "product", label: "کالا" },
    { value: "service", label: "خدمات" },
    { value: "other",   label: "سایر" },
];

export default class ProductsSection extends SectionBase {
    constructor(props={}) { super(props); this._products=[]; this._invProducts=[]; }

    async template() {
        return `
            <div style="display:flex;gap:10px;margin-bottom:14px;flex-wrap:wrap;">
                <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;">
                <select data-ref="typeFilter" style="padding:7px 12px;border:1.5px solid #d1d5db;border-radius:8px;font-size:13px;">
                    <option value="">همه نوع‌ها</option>
                    ${PRODUCT_TYPES.map(t=>`<option value="${t.value}">${t.label}</option>`).join("")}
                </select>
            </div>
            <div class="entity-grid" data-ref="grid"></div>
        `;
    }

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

    async _loadInvProducts() {
        try {
            const res = await this.api.get("/inv/products");
            this._invProducts = res?.data ?? [];
        } catch { this._invProducts = []; }
    }

    async _load() {
        const grid   = this.ref("grid");
        const search = this.ref("searchIn").value.trim();
        const type   = this.ref("typeFilter").value;
        grid.innerHTML = `<div class="acc-loading" style="grid-column:1/-1"><div class="acc-spinner"></div></div>`;
        try {
            const params = {};
            if (search) params.search = search;
            if (type)   params.type   = type;
            const res = await this.api.get("/sales/products", params);
            this._products = res?.data ?? [];
            this._render(grid);
        } catch { grid.innerHTML=`<div class="acc-error" style="grid-column:1/-1">خطا در بارگذاری</div>`; }
    }

    _render(grid) {
        if (!this._products.length) {
            grid.innerHTML=`<div class="acc-empty" style="grid-column:1/-1">محصولی یافت نشد.</div>`;
            return;
        }
        grid.innerHTML="";
        this._products.forEach(p => {
            const typeLabel = PRODUCT_TYPES.find(t=>t.value===p.type)?.label ?? p.type ?? "";
            const card = document.createElement("div");
            card.className = "entity-card";
            card.innerHTML=`
                <div class="entity-card__code">${this.escape(p.sku||p.code||"")}</div>
                <div class="entity-card__name">${this.escape(p.name)}</div>
                <div class="entity-card__meta">
                    <span style="display:inline-block;background:#eff6ff;color:#2563eb;border-radius:6px;padding:1px 7px;font-size:11px;font-weight:600;margin-bottom:4px;">${this.escape(typeLabel)}</span><br>
                    ${p.sale_price  ? `💰 فروش: ${new Intl.NumberFormat("fa-IR").format(p.sale_price)}<br>`  : ""}
                    ${p.cost_price  ? `📥 خرید: ${new Intl.NumberFormat("fa-IR").format(p.cost_price)}<br>`  : ""}
                    ${p.vat_rate    ? `🧾 مالیات: ${p.vat_rate}%<br>`                                         : ""}
                    ${p.stock_qty!=null ? `📦 موجودی: ${p.stock_qty}<br>` : ""}
                    ${p.inv_product_id ? `🔗 <span style="color:#10b981;font-weight:600;">متصل به انبار</span>` : `<span style="color:#94a3b8;">بدون اتصال انبار</span>`}
                </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--danger    acc-btn--sm" data-action="del">حذف</button>
                </div>
            `;
            card.querySelector("[data-action='edit']").addEventListener("click", ()=>this._openForm(p));
            card.querySelector("[data-action='del']" ).addEventListener("click", ()=>this._delete(p));
            grid.appendChild(card);
        });
    }

    _openForm(p=null) {
        const typeOpts = PRODUCT_TYPES.map(t=>
            `<option value="${t.value}" ${p?.type===t.value?"selected":""}>${t.label}</option>`
        ).join("");
        const ov=document.createElement("div"); ov.className="acc-modal-overlay";
        ov.innerHTML=`
            <div class="acc-modal" style="max-width:540px;">
                <button class="acc-modal__close">✕</button>
                <div class="acc-modal__title">${p?"ویرایش محصول":"محصول / خدمت جدید"}</div>
                <form>
                    <div class="doc-form-row">
                        <div class="acc-form-group"><label>کد / SKU</label><input name="sku" value="${this.escape(p?.sku||"")}"></div>
                        <div class="acc-form-group"><label>نام *</label><input name="name" value="${this.escape(p?.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><input name="unit" value="${this.escape(p?.unit||"")}"></div>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group"><label>قیمت فروش (ریال)</label><input name="sale_price" type="number" step="1" value="${p?.sale_price||0}"></div>
                        <div class="acc-form-group"><label>قیمت خرید (ریال)</label><input name="cost_price" type="number" step="1" value="${p?.cost_price||0}"></div>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group"><label>نرخ مالیات (%)</label><input name="vat_rate" type="number" step="0.01" min="0" max="100" value="${p?.vat_rate||0}"></div>
                        <div class="acc-form-group"><label>موجودی اولیه</label><input name="stock_qty" type="number" step="1" value="${p?.stock_qty??0}"></div>
                    </div>
                    <div class="acc-form-group">
                        <label>🏭 اتصال به محصول انبار (برای ثبت خودکار حرکت)</label>
                        <select name="inv_product_id">
                            <option value="">— بدون اتصال (فقط حسابداری) —</option>
                            ${this._invProducts.map(ip =>
                                `<option value="${ip.id}" ${p?.inv_product_id == ip.id ? "selected" : ""}>${this.escape(ip.code)} — ${this.escape(ip.name)}</option>`
                            ).join("")}
                        </select>
                        <small style="color:#94a3b8;font-size:11px;">اگر متصل شود، با نهایی‌شدن فاکتور خودکار سند انبار صادر می‌شود</small>
                    </div>
                    <div class="acc-form-group"><label>توضیحات</label><textarea name="description" rows="2">${this.escape(p?.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">${p?"ذخیره":"افزودن"}</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 e=>{
            e.preventDefault();
            const fd=new FormData(e.target);
            const body=Object.fromEntries(fd.entries());
            const btn=e.target.querySelector("[type='submit']");
            btn.disabled=true; btn.textContent="در حال ذخیره...";
            try{
                if(p) await this.api.put(`/sales/products/${p.id}`,body);
                else  await this.api.post("/sales/products",body);
                close(); await this._load();
            } catch(err){ alert("خطا: "+(err?.message??"")); btn.disabled=false; btn.textContent=p?"ذخیره":"افزودن"; }
        });
    }

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