/**
 * CarriersSection.js — شرکت‌های حمل و نقل
 */
import SectionBase from "../../accounting/SectionBase.js";
import LocationPicker from "../../gis/components/LocationPicker.js";

export default class CarriersSection extends SectionBase {

    async template() {
        return `
        <div class="acc-section-wrap">
            <div class="acc-toolbar">
                <h2 class="acc-section-title">🏢 شرکت‌های حمل</h2>
                <div style="display:flex;gap:8px;">
                    <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 this._load();
        this.on(this.ref("refreshBtn"), "click", () => this._load());
        this.on(this.ref("addBtn"),     "click", () => this._openModal());
    }

    async _load() {
        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res = await this.api.get("/ship/carriers");
            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(c => `
            <div style="border:1px solid #e2e8f0;border-radius:10px;padding:14px;background:#fff;">
                <div style="font-weight:700;font-size:14px;">🏢 ${this.escape(c.name)}</div>
                ${c.contact_name ? `<div style="font-size:12px;color:#475569;margin-top:6px;">👤 ${this.escape(c.contact_name)}</div>` : ''}
                ${c.phone ? `<div style="font-size:12px;color:#475569;direction:ltr;text-align:right;">📞 ${this.escape(c.phone)}</div>` : ''}
                ${c.email ? `<div style="font-size:11px;color:#94a3b8;direction:ltr;text-align:right;">${this.escape(c.email)}</div>` : ''}
                <div style="font-size:12px;color:#3b82f6;margin-top:8px;font-weight:700;">📦 ${c.shipment_count} محموله</div>
                <div style="display:flex;gap:4px;margin-top:10px;">
                    <button class="acc-btn acc-btn--xs" data-edit="${c.id}">✏️</button>
                    <button class="acc-btn acc-btn--xs" data-loc="${c.id}" data-name="${this.escape(c.name)}" style="background:#dbeafe;color:#1e40af;">📍</button>
                    <button class="acc-btn acc-btn--xs gis-btn--danger" data-del="${c.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-del]").forEach(b =>
            b.addEventListener("click", async () => {
                if (!confirm("حذف؟")) return;
                try { await this.api.delete(`/ship/carriers/${b.dataset.del}`); this._load(); }
                catch(e) { alert("خطا: " + (e?.message ?? "")); }
            })
        );
        this.ref("wrap").querySelectorAll("[data-loc]").forEach(b =>
            b.addEventListener("click", () => LocationPicker.openModal({
                api: this.api, entityType: 'carrier',
                entityId: parseInt(b.dataset.loc), entityName: b.dataset.name,
            }))
        );
    }

    _openModal(c = null) {
        const isEdit = !!c;
        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">${isEdit ? '✏️ ویرایش' : '➕ شرکت حمل جدید'}</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" required value="${this.escape(c?.name ?? '')}"></div>
                </div>
                <div class="acc-form-group"><label>نام رابط</label>
                    <input name="contact_name" value="${this.escape(c?.contact_name ?? '')}">
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>تلفن</label>
                        <input name="phone" value="${this.escape(c?.phone ?? '')}" dir="ltr">
                    </div>
                    <div class="acc-form-group"><label>ایمیل</label>
                        <input name="email" type="email" value="${this.escape(c?.email ?? '')}" dir="ltr">
                    </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">ذخیره</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(`/ship/carriers/${c.id}`, body);
                else        await this.api.post("/ship/carriers", body);
                close(); this._load();
            } catch(e) { alert("خطا: " + (e?.message ?? "")); }
        });
    }

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