/**
 * SuppliersSection.js — مدیریت تأمین‌کنندگان (با LocationPicker)
 */
import SectionBase from "../../accounting/SectionBase.js";
import LocationPicker from "../../gis/components/LocationPicker.js";

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

    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", ()  => this._load(this.ref("searchIn").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("/purchase/suppliers", search ? {search} : {});
            this._suppliers = res?.data ?? [];
            this._render(grid);
        } catch { grid.innerHTML=`<div class="acc-error" style="grid-column:1/-1">خطا در بارگذاری</div>`; }
    }

    _render(grid) {
        if (!this._suppliers.length) {
            grid.innerHTML=`<div class="acc-empty" style="grid-column:1/-1">تأمین‌کننده‌ای یافت نشد.</div>`;
            return;
        }
        grid.innerHTML="";
        this._suppliers.forEach(s => {
            const card = document.createElement("div");
            card.className = "entity-card";
            card.innerHTML=`
                <div class="entity-card__code">${this.escape(s.code||"")}</div>
                <div class="entity-card__name">${this.escape(s.name)}</div>
                <div class="entity-card__meta">
                    ${s.phone      ? `📞 ${this.escape(s.phone)}<br>`      : ""}
                    ${s.tax_id     ? `🪪 ${this.escape(s.tax_id)}<br>`     : ""}
                    ${s.bank_iban  ? `🏦 ${this.escape(s.bank_iban)}<br>`  : ""}
                    ${s.contact_person ? `👤 ${this.escape(s.contact_person)}` : ""}
                </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(s));
            card.querySelector("[data-action='del']" ).addEventListener("click", ()=>this._delete(s));
            card.querySelector("[data-action='loc']").addEventListener("click", () => LocationPicker.openModal({
                api: this.api, entityType: 'supplier', entityId: s.id, entityName: s.name,
            }));
            grid.appendChild(card);
        });
    }

    _openForm(s=null) {
        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">${s?"ویرایش تأمین‌کننده":"تأمین‌کننده جدید"}</div>
                <form>
                    <div class="doc-form-row">
                        <div class="acc-form-group"><label>کد</label><input name="code" value="${this.escape(s?.code||"")}"></div>
                        <div class="acc-form-group"><label>نام شرکت / شخص *</label><input name="name" value="${this.escape(s?.name||"")}" required></div>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group"><label>تلفن</label><input name="phone" value="${this.escape(s?.phone||"")}"></div>
                        <div class="acc-form-group"><label>ایمیل</label><input name="email" type="email" value="${this.escape(s?.email||"")}"></div>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group"><label>شناسه مالیاتی</label><input name="tax_id" value="${this.escape(s?.tax_id||"")}"></div>
                        <div class="acc-form-group"><label>نام رابط</label><input name="contact_person" value="${this.escape(s?.contact_person||"")}"></div>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group"><label>شماره شبا / IBAN</label><input name="bank_iban" value="${this.escape(s?.bank_iban||"")}"></div>
                        <div class="acc-form-group"><label>نام بانک</label><input name="bank_name" value="${this.escape(s?.bank_name||"")}"></div>
                    </div>
                    <div class="acc-form-group"><label>آدرس</label><textarea name="address" rows="2">${this.escape(s?.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">${s?"ذخیره":"افزودن"}</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(s) await this.api.put(`/purchase/suppliers/${s.id}`,body);
                else  await this.api.post("/purchase/suppliers",body);
                close(); await this._load();
            } catch(err){ alert("خطا: "+(err?.message??"")); btn.disabled=false; btn.textContent=s?"ذخیره":"افزودن"; }
        });
    }

    async _delete(s) {
        if(!confirm(`حذف تأمین‌کننده «${s.name}»؟`))return;
        try{ await this.api.delete(`/purchase/suppliers/${s.id}`); await this._load(); }
        catch(err){ alert("خطا: "+(err?.message??"")); }
    }
}
