/**
 * LayersSection.js — مدیریت لایه‌ها (مناطق + محلات)
 * CRUD برای مناطق شهرداری و محلات
 */
import SectionBase from "../../accounting/SectionBase.js";

export default class LayersSection extends SectionBase {

    constructor(props={}) {
        super(props);
        this._districts     = [];
        this._neighborhoods = [];
        this._activeTab     = 'districts';
    }

    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;margin-bottom:20px;flex-wrap:wrap;align-items:center;">
                <button class="acc-btn ${this._activeTab==='districts'?'acc-btn--primary':'acc-btn--secondary'}"
                    data-tab="districts">🏙️ مناطق شهرداری</button>
                <button class="acc-btn ${this._activeTab==='neighborhoods'?'acc-btn--primary':'acc-btn--secondary'}"
                    data-tab="neighborhoods">🏘️ محلات</button>
                <div style="margin-right:auto;">
                    <button class="acc-btn acc-btn--secondary" data-ref="importBtn"
                        style="background:#f0fdf4;border-color:#86efac;color:#166534;">
                        📥 ایمپورت JSON پارسل‌ها
                    </button>
                </div>
            </div>
            <div data-ref="body"></div>
        `;
        root.querySelectorAll('[data-tab]').forEach(btn => {
            btn.addEventListener('click', () => {
                this._activeTab = btn.dataset.tab;
                this._render();
            });
        });
        this._bindRef();
        this.ref('importBtn')?.addEventListener('click', () => this._openImportModal());
        if (this._activeTab === 'districts') await this._renderDistricts();
        else await this._renderNeighborhoods();
    }

    _bindRef() {
        this.ref('root')?.querySelectorAll('[data-ref]').forEach(el => { this.refs[el.dataset.ref]=el; });
    }

    /* ── مناطق ──────────────────────────────────────────────── */
    async _renderDistricts() {
        const body = this.ref('body');
        body.innerHTML = `<div class="acc-loading"><div class="acc-spinner"></div></div>`;
        try {
            const res = await this.api.get('/gis/districts');
            this._districts = res?.data ?? [];
        } catch { body.innerHTML = `<div class="acc-error">خطا در بارگذاری</div>`; return; }

        body.innerHTML = `
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
                <span style="font-weight:700;color:#1e293b;">${this._districts.length} منطقه ثبت‌شده</span>
                <button class="acc-btn acc-btn--primary acc-btn--sm" data-action="add-district">➕ منطقه جدید</button>
            </div>
            <div data-ref="distList"></div>
        `;
        body.querySelector('[data-ref]') && (this.refs['distList'] = body.querySelector('[data-ref="distList"]'));
        body.querySelector('[data-action="add-district"]')?.addEventListener('click', () => this._openDistrictModal());

        const list = body.querySelector('[data-ref="distList"]');
        if (!this._districts.length) { list.innerHTML = `<div class="acc-empty">منطقه‌ای ثبت نشده.</div>`; return; }
        this._districts.forEach(d => {
            const row = document.createElement('div');
            row.className = 'gis-layer-row';
            row.style.borderRight = `4px solid ${d.color||'#3b82f6'}`;
            row.innerHTML = `
                <div class="gis-layer-dot" style="background:${d.color||'#3b82f6'}"></div>
                <div style="flex:1;">
                    <div style="font-weight:700;font-size:14px;color:#1e293b;">${this.escape(d.name)}</div>
                    <div style="font-size:12px;color:#64748b;">
                        ${d.neighborhood_count||0} محله | ${d.parcel_count||0} پارسل
                        ${d.assigned_user_name ? ' | 👤 '+this.escape(d.assigned_user_name) : ''}
                    </div>
                </div>
                <button class="acc-btn acc-btn--secondary acc-btn--sm" data-edit="${d.id}">ویرایش</button>
                <button class="acc-btn acc-btn--danger acc-btn--sm" data-del="${d.id}">حذف</button>
            `;
            row.querySelector(`[data-edit]`)?.addEventListener('click', () => this._openDistrictModal(d));
            row.querySelector(`[data-del]`)?.addEventListener('click', async () => {
                if (!confirm(`حذف منطقه "${d.name}"؟`)) return;
                await this.api.delete(`/gis/districts/${d.id}`);
                this._renderDistricts();
            });
            list.appendChild(row);
        });
    }

    _openDistrictModal(d = null) {
        const ov = document.createElement('div'); ov.className = 'acc-modal-overlay';
        ov.innerHTML = `
            <div class="acc-modal" style="max-width:400px;">
                <button class="acc-modal__close">✕</button>
                <div class="acc-modal__title">${d ? 'ویرایش' : 'افزودن'} منطقه</div>
                <form>
                    <div class="doc-form-row">
                        <div class="acc-form-group"><label>نام منطقه *</label>
                            <input name="name" required value="${this.escape(d?.name||'')}">
                        </div>
                        <div class="acc-form-group"><label>کد</label>
                            <input name="code" value="${this.escape(d?.code||'')}">
                        </div>
                    </div>
                    <div class="acc-form-group"><label>شهر</label>
                        <input name="city" value="${this.escape(d?.city||'تهران')}">
                    </div>
                    <div class="acc-form-group"><label>کارشناس مسئول</label>
                        <input name="assigned_user_name" value="${this.escape(d?.assigned_user_name||'')}">
                    </div>
                    <div class="acc-form-group"><label>رنگ روی نقشه</label>
                        <input type="color" name="color" value="${d?.color||'#3b82f6'}" style="width:60px;height:36px;cursor:pointer;">
                    </div>
                    <div class="acc-form-group"><label>یادداشت</label>
                        <textarea name="notes" rows="2">${this.escape(d?.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">${d ? 'ذخیره' : 'افزودن'}</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());
            const btn = ev.target.querySelector('[type="submit"]');
            btn.disabled = true;
            try {
                if (d) await this.api.put(`/gis/districts/${d.id}`, body);
                else   await this.api.post('/gis/districts', body);
                close(); await this._renderDistricts();
            } catch(err) { alert('خطا: '+(err?.message||'')); btn.disabled=false; }
        });
    }

    /* ── محلات ──────────────────────────────────────────────── */
    async _renderNeighborhoods() {
        const body = this.ref('body');
        body.innerHTML = `<div class="acc-loading"><div class="acc-spinner"></div></div>`;
        try {
            const [dRes, nRes] = await Promise.all([
                this.api.get('/gis/districts'),
                this.api.get('/gis/neighborhoods'),
            ]);
            this._districts     = dRes?.data ?? [];
            this._neighborhoods = nRes?.data ?? [];
        } catch { body.innerHTML = `<div class="acc-error">خطا</div>`; return; }

        const trendIcon = {growing:'🔥',stable:'➡️',declining:'📉'};
        const trendLabel = {growing:'رو به رشد',stable:'پایدار',declining:'رو به افول'};

        body.innerHTML = `
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
                <span style="font-weight:700;color:#1e293b;">${this._neighborhoods.length} محله ثبت‌شده</span>
                <button class="acc-btn acc-btn--primary acc-btn--sm" data-action="add-n">➕ محله جدید</button>
            </div>
            <div id="n-list"></div>
        `;
        body.querySelector('[data-action="add-n"]')?.addEventListener('click', () => this._openNeighborhoodModal());
        const list = body.querySelector('#n-list');
        if (!this._neighborhoods.length) { list.innerHTML = `<div class="acc-empty">محله‌ای ثبت نشده.</div>`; return; }
        this._neighborhoods.forEach(n => {
            const row = document.createElement('div');
            row.className = 'gis-layer-row';
            row.innerHTML = `
                <div style="flex:1;">
                    <div style="font-weight:700;font-size:14px;color:#1e293b;">${this.escape(n.name)}</div>
                    <div style="font-size:12px;color:#64748b;margin-top:2px;">
                        🏙️ ${this.escape(n.district_name||'')} |
                        ${trendIcon[n.development_trend]||''} ${trendLabel[n.development_trend]||''}
                        ${n.has_metro=='1' ? ' | 🚇 مترو' : ''}
                        ${n.parcel_count ? ' | 📁 '+n.parcel_count+' پارسل' : ''}
                        ${n.assigned_user_name ? ' | 👤 '+this.escape(n.assigned_user_name) : ''}
                    </div>
                </div>
                <button class="acc-btn acc-btn--secondary acc-btn--sm" data-edit="${n.id}">ویرایش</button>
                <button class="acc-btn acc-btn--danger acc-btn--sm" data-del="${n.id}">حذف</button>
            `;
            row.querySelector('[data-edit]')?.addEventListener('click', () => this._openNeighborhoodModal(n));
            row.querySelector('[data-del]')?.addEventListener('click', async () => {
                if (!confirm(`حذف محله "${n.name}"؟`)) return;
                await this.api.delete(`/gis/neighborhoods/${n.id}`);
                this._renderNeighborhoods();
            });
            list.appendChild(row);
        });
    }

    _openNeighborhoodModal(n = null) {
        const distOpts = `<option value="">— انتخاب منطقه —</option>` +
            this._districts.map(d => `<option value="${d.id}" ${d.id==n?.district_id?'selected':''}>${this.escape(d.name)}</option>`).join('');

        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">${n?'ویرایش':'افزودن'} محله</div>
                <form>
                    <div class="acc-form-group"><label>نام محله *</label>
                        <input name="name" required value="${this.escape(n?.name||'')}">
                    </div>
                    <div class="acc-form-group"><label>منطقه *</label>
                        <select name="district_id" required>${distOpts}</select>
                    </div>
                    <div class="doc-form-row">
                        <div class="acc-form-group"><label>کارشناس مسئول</label>
                            <input name="assigned_user_name" value="${this.escape(n?.assigned_user_name||'')}">
                        </div>
                        <div class="acc-form-group"><label>روند توسعه</label>
                            <select name="development_trend">
                                <option value="growing" ${n?.development_trend==='growing'?'selected':''}>🔥 رو به رشد</option>
                                <option value="stable"  ${n?.development_trend==='stable'?'selected':''}>➡️ پایدار</option>
                                <option value="declining" ${n?.development_trend==='declining'?'selected':''}>📉 رو به افول</option>
                            </select>
                        </div>
                    </div>
                    <div class="acc-form-group"><label>کاربری غالب</label>
                        <input name="dominant_use" value="${this.escape(n?.dominant_use||'')}">
                    </div>
                    <div style="display:flex;gap:16px;margin:10px 0;font-size:13px;">
                        <label><input type="checkbox" name="has_metro" value="1" ${n?.has_metro=='1'?'checked':''}> 🚇 مترو</label>
                        <label><input type="checkbox" name="has_brt"   value="1" ${n?.has_brt=='1'?'checked':''}> 🚌 BRT</label>
                    </div>
                    <div class="acc-form-group"><label>وضعیت زیرساخت</label>
                        <select name="infrastructure">
                            <option value="complete" ${n?.infrastructure==='complete'?'selected':''}>✅ کامل</option>
                            <option value="partial"  ${n?.infrastructure==='partial'?'selected':''}>🟡 ناقص</option>
                            <option value="poor"     ${n?.infrastructure==='poor'?'selected':''}>🔴 ضعیف</option>
                        </select>
                    </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">${n?'ذخیره':'افزودن'}</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());
            body.has_metro = body.has_metro ? 1 : 0;
            body.has_brt   = body.has_brt   ? 1 : 0;
            const btn = ev.target.querySelector('[type="submit"]');
            btn.disabled = true;
            try {
                if (n) await this.api.put(`/gis/neighborhoods/${n.id}`, body);
                else   await this.api.post('/gis/neighborhoods', body);
                close(); await this._renderNeighborhoods();
            } catch(err) { alert('خطا: '+(err?.message||'')); btn.disabled=false; }
        });
    }

    /* ── مودال ایمپورت JSON ──────────────────────────────────── */
    _openImportModal() {
        const ov = document.createElement('div');
        ov.className = 'acc-modal-overlay';
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:500px;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">📥 ایمپورت JSON پارسل‌ها</div>

            <div style="background:#eff6ff;border:1px solid #bfdbfe;border-radius:8px;
                        padding:12px;font-size:12px;color:#1e40af;margin-bottom:16px;line-height:1.8;">
                <b>فرمت قابل قبول:</b><br>
                • فیلد <code>Geom</code>: WKT POLYGON<br>
                • فیلد <code>Code</code>/<code>Name</code>: کد پلاک<br>
                • فیلد <code>parsel</code>: کدهای نوسازی (comma-separated)
            </div>

            <div class="acc-form-group">
                <label>مسیر فایل JSON روی سرور</label>
                <input id="_imp_path" placeholder="مثال: C:/data/shiraz_parcels.json"
                    style="direction:ltr;font-size:12px;font-family:monospace;">
            </div>
            <div class="acc-form-group">
                <label>منطقه شهرداری (اختیاری)</label>
                <select id="_imp_district">
                    <option value="">— بدون تخصیص —</option>
                </select>
            </div>
            <div class="acc-form-group">
                <label style="display:flex;gap:8px;align-items:center;cursor:pointer;">
                    <input type="checkbox" id="_imp_skip" checked>
                    رد کردن پارسل‌های تکراری (بر اساس کد)
                </label>
            </div>

            <div id="_imp_result" style="display:none;padding:12px;border-radius:8px;
                font-size:13px;margin-top:10px;"></div>

            <div class="acc-modal__actions">
                <button class="acc-btn acc-btn--secondary" data-action="cancel">انصراف</button>
                <button class="acc-btn acc-btn--primary" id="_imp_btn">📥 شروع ایمپورت</button>
            </div>
        </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(); });

        // بارگذاری مناطق
        this.api.get('/gis/districts').then(res => {
            const sel = ov.querySelector('#_imp_district');
            (res?.data||[]).forEach(d => {
                sel.innerHTML += `<option value="${d.id}">${this.escape(d.name)}</option>`;
            });
        });

        // ایمپورت
        ov.querySelector('#_imp_btn').addEventListener('click', async () => {
            const btn      = ov.querySelector('#_imp_btn');
            const filePath = ov.querySelector('#_imp_path').value.trim();
            const distId   = ov.querySelector('#_imp_district').value;
            const skipDup  = ov.querySelector('#_imp_skip').checked;
            const result   = ov.querySelector('#_imp_result');

            if (!filePath) { alert('مسیر فایل را وارد کنید'); return; }

            btn.disabled = true;
            btn.textContent = '⏳ در حال ایمپورت...';
            result.style.display = 'none';

            try {
                const res = await this.api.post('/gis/import', {
                    file_path:        filePath,
                    district_id:      distId || null,
                    skip_duplicates:  skipDup,
                });

                const ok = res?.success;
                result.style.display = 'block';
                result.style.background = ok ? '#f0fdf4' : '#fef2f2';
                result.style.border = `1px solid ${ok ? '#86efac' : '#fca5a5'}`;
                result.style.color  = ok ? '#166534' : '#991b1b';

                if (ok) {
                    result.innerHTML = `
                        ✅ ایمپورت کامل شد<br>
                        📌 درج شده: <b>${res.inserted}</b><br>
                        ⏭ رد شده (تکراری): <b>${res.skipped}</b><br>
                        ❌ خطا: <b>${res.errors?.length||0}</b>
                        ${res.errors?.length ? '<br><small>'+res.errors.slice(0,3).map(e=>this.escape(e)).join('<br>')+'</small>' : ''}
                    `;
                } else {
                    result.textContent = '❌ ' + (res?.message || 'خطا');
                }
            } catch(err) {
                result.style.display = 'block';
                result.style.background = '#fef2f2';
                result.style.border = '1px solid #fca5a5';
                result.style.color = '#991b1b';
                result.textContent = '❌ ' + (err?.message || 'خطای ارتباطی');
            }

            btn.disabled = false;
            btn.textContent = '📥 شروع ایمپورت';
        });
    }
}
