/**
 * CustomersSection.js — مدیریت مشتریان (با LocationPicker)
 */
import SectionBase from "../../accounting/SectionBase.js";
import LocationPicker from "../../gis/components/LocationPicker.js";

export default class CustomersSection extends SectionBase {
    constructor(props={}) { super(props); this._customers=[]; }

    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;">
            </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", (e) => this._load(e.target.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("/sales/customers", search ? {search} : {});
            this._customers = res?.data ?? [];
            this._render(grid);
        } catch { grid.innerHTML=`<div class="acc-error" style="grid-column:1/-1">خطا</div>`; }
    }

    _render(grid) {
        if (!this._customers.length) { grid.innerHTML=`<div class="acc-empty" style="grid-column:1/-1">مشتری‌ای یافت نشد.</div>`; return; }
        grid.innerHTML="";
        this._customers.forEach(c => {
            const card = document.createElement("div");
            card.className = "entity-card";
            card.innerHTML=`
                <div class="entity-card__code">${this.escape(c.code||"")}</div>
                <div class="entity-card__name">${this.escape(c.name)}</div>
                <div class="entity-card__meta">
                    ${c.phone ? `📞 ${this.escape(c.phone)}<br>`: ""}
                    ${c.tax_id ? `🪪 ${this.escape(c.tax_id)}<br>` : ""}
                    ${c.credit_limit>0 ? `💳 سقف اعتبار: ${new Intl.NumberFormat("fa-IR").format(c.credit_limit)}` : ""}
                </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" data-action="loc" style="background:#dbeafe;color:#1e40af;">📍 موقعیت</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(c));
            card.querySelector("[data-action='del']" ).addEventListener("click", ()=>this._delete(c));
            card.querySelector("[data-action='loc']").addEventListener("click", () => LocationPicker.openModal({
                api: this.api, entityType: 'customer', entityId: c.id, entityName: c.name,
            }));
            grid.appendChild(card);
        });
    }

    _openForm(c=null) {
        const ov=document.createElement("div"); ov.className="acc-modal-overlay";
        ov.innerHTML=`
            <div class="acc-modal">
                <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><input name="phone" value="${this.escape(c?.phone||"")}"></div>
                        <div class="acc-form-group"><label>ایمیل</label><input name="email" type="email" value="${this.escape(c?.email||"")}"></div>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group"><label>شناسه مالیاتی</label><input name="tax_id" value="${this.escape(c?.tax_id||"")}"></div>
                        <div class="acc-form-group"><label>سقف اعتبار (ریال)</label><input name="credit_limit" type="number" value="${c?.credit_limit||0}"></div>
                    </div>
                    <div class="acc-form-group"><label>آدرس</label><textarea name="address" rows="2">${this.escape(c?.address||"")}</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">${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",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());
            try{
                if(c) await this.api.put(`/sales/customers/${c.id}`,body);
                else  await this.api.post("/sales/customers",body);
                close(); await this._load();
            } catch(err){ alert("خطا: "+(err?.message??"")); }
        });
    }

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