/**
 * CustomersSection.js — دایرکتوری مشتریان
 */
import SectionBase from "../../accounting/SectionBase.js";

export default class CustomersSection extends SectionBase {

    constructor(props={}) {
        super(props);
        this._customers = [];
        this._search    = '';
    }

    async template() { return `<div data-ref="root"></div>`; }

    async afterRender() { await this._render(); }

    async _render() {
        const root = this.ref('root');
        root.innerHTML = `
        <div style="display:flex;gap:10px;align-items:center;margin-bottom:16px;flex-wrap:wrap;">
            <input type="text" class="acc-input" data-ref="searchInp" placeholder="🔍 نام، کد ملی یا تلفن..."
                style="flex:1;min-width:200px;">
            <button class="acc-btn acc-btn--primary acc-btn--sm" data-ref="addBtn">➕ مشتری جدید</button>
            <button class="acc-btn acc-btn--secondary acc-btn--sm" data-ref="refreshBtn">🔄</button>
        </div>
        <div data-ref="body"></div>`;

        root.querySelectorAll('[data-ref]').forEach(el => { this.refs[el.dataset.ref] = el; });
        this.on(this.ref('searchInp'), 'input', () => { this._search = this.ref('searchInp').value; this._load(); });
        this.on(this.ref('addBtn'),    'click',  () => this._openCustomerModal());
        this.on(this.ref('refreshBtn'),'click',  () => this._load());

        await this._load();
    }

    async _load() {
        const body = this.ref('body');
        body.innerHTML = `<div class="acc-loading"><div class="acc-spinner"></div></div>`;
        const params = this._search ? { search: this._search } : {};
        try {
            const res = await this.api.get('/sale-customers', params);
            this._customers = res?.data ?? [];
            this._renderList();
        } catch {
            body.innerHTML = `<div class="acc-error">خطا</div>`;
        }
    }

    _renderList() {
        const body = this.ref('body');
        const fmt  = v => new Intl.NumberFormat('fa-IR').format(Math.round(Number(v||0)));
        if (!this._customers.length) {
            body.innerHTML = `<div class="acc-empty">مشتری‌ای ثبت نشده.</div>`;
            return;
        }
        body.innerHTML = `
        <div class="customer-grid">
            ${this._customers.map(c => `
            <div class="customer-card" data-id="${c.id}">
                <div style="display:flex;justify-content:space-between;align-items:start;">
                    <div>
                        <div style="font-size:15px;font-weight:800;color:#1e293b;">
                            ${c.type==='company'?'🏢':'👤'} ${this.escape(c.name)}
                        </div>
                        ${c.company_name ? `<div style="font-size:12px;color:#64748b;">🏢 ${this.escape(c.company_name)}</div>` : ''}
                        ${c.national_id  ? `<div style="font-size:12px;color:#94a3b8;">کد ملی: ${c.national_id}</div>` : ''}
                        ${c.phone        ? `<div style="font-size:12px;color:#64748b;">📞 ${c.phone}</div>` : ''}
                    </div>
                    <div style="text-align:left;">
                        <div style="font-size:18px;font-weight:800;color:#3b82f6;">${c.sale_count||0}</div>
                        <div style="font-size:10px;color:#94a3b8;">واحد خریداری</div>
                    </div>
                </div>
                ${c.total_purchased > 0 ? `
                <div style="font-size:12px;color:#10b981;margin-top:6px;font-weight:600;">
                    💰 مجموع خرید: ${fmt(c.total_purchased)} ریال
                </div>` : ''}
                <div style="display:flex;gap:6px;margin-top:10px;">
                    <button class="gis-btn gis-btn--secondary gis-btn--sm" data-edit="${c.id}">✏️ ویرایش</button>
                    ${!c.sale_count ? `<button class="gis-btn gis-btn--danger gis-btn--sm" data-del="${c.id}">🗑️ حذف</button>` : ''}
                </div>
            </div>`).join('')}
        </div>`;

        body.querySelectorAll('[data-edit]').forEach(btn => {
            const c = this._customers.find(c=>String(c.id)===btn.dataset.edit);
            if (c) btn.addEventListener('click', ()=>this._openCustomerModal(c));
        });
        body.querySelectorAll('[data-del]').forEach(btn => {
            btn.addEventListener('click', async () => {
                if (!confirm('حذف این مشتری؟')) return;
                try {
                    await this.api.delete(`/sale-customers/${btn.dataset.del}`);
                    this._toast('🗑️ مشتری حذف شد');
                    this._load();
                } catch(err) { alert('خطا: '+(err?.message||'')); }
            });
        });
    }

    _openCustomerModal(c = null) {
        const isEdit = !!c;
        const cu = c || {};

        const ov = document.createElement('div'); ov.className = 'acc-modal-overlay';
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:440px;max-height:90vh;overflow-y:auto;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">👤 ${isEdit?'ویرایش':'مشتری جدید'}</div>
            <form>
                <div style="display:flex;gap:12px;margin-bottom:12px;">
                    <label style="font-size:13px;display:flex;gap:6px;align-items:center;">
                        <input type="radio" name="type" value="individual" ${cu.type!=='company'?'checked':''}> شخص حقیقی
                    </label>
                    <label style="font-size:13px;display:flex;gap:6px;align-items:center;">
                        <input type="radio" name="type" value="company" ${cu.type==='company'?'checked':''}> شخص حقوقی
                    </label>
                </div>
                <div class="acc-form-group"><label>نام *</label>
                    <input name="name" required value="${this.escape(cu.name||'')}">
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>کد ملی / شناسه ملی</label>
                        <input name="national_id" value="${this.escape(cu.national_id||'')}">
                    </div>
                    <div class="acc-form-group"><label>تلفن</label>
                        <input name="phone" type="tel" value="${this.escape(cu.phone||'')}">
                    </div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>تلفن دوم</label>
                        <input name="phone2" value="${this.escape(cu.phone2||'')}">
                    </div>
                    <div class="acc-form-group"><label>ایمیل</label>
                        <input name="email" type="email" value="${this.escape(cu.email||'')}">
                    </div>
                </div>
                <div class="acc-form-group"><label>نام شرکت</label>
                    <input name="company_name" value="${this.escape(cu.company_name||'')}">
                </div>
                <div class="acc-form-group"><label>آدرس</label>
                    <textarea name="address" rows="2">${this.escape(cu.address||'')}</textarea>
                </div>
                <div class="acc-form-group"><label>یادداشت</label>
                    <textarea name="notes" rows="2">${this.escape(cu.notes||'')}</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">${isEdit?'ذخیره':'ثبت مشتری'}</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', ev => { if(ev.target===ov) close(); });
        ov.querySelector('form').addEventListener('submit', async ev => {
            ev.preventDefault();
            const body = Object.fromEntries(new FormData(ev.target).entries());
            ['phone2','email','company_name','address','notes'].forEach(k=>{ if(!body[k]) delete body[k]; });
            const btn = ev.target.querySelector('[type="submit"]');
            btn.disabled = true;
            try {
                if (isEdit) await this.api.put(`/sale-customers/${c.id}`, body);
                else        await this.api.post('/sale-customers', body);
                close(); this._toast(isEdit?'✅ ویرایش شد':'✅ مشتری ثبت شد');
                this._load();
            } catch(err) { alert('خطا: '+(err?.message||'')); btn.disabled=false; }
        });
    }

    _toast(msg, bg='#10b981') {
        const t = document.createElement('div');
        t.style.cssText = `position:fixed;bottom:24px;left:24px;background:${bg};color:#fff;padding:12px 20px;border-radius:10px;font-size:13px;font-weight:600;z-index:9999;direction:rtl;`;
        t.textContent = msg; document.body.appendChild(t);
        setTimeout(()=>t.remove(), 3000);
    }
}
