/**
 * LocationPicker.js — انتخاب موقعیت روی نقشه
 *
 * استفاده در هر فرم:
 *   import LocationPicker from '../../gis/components/LocationPicker.js';
 *
 *   new LocationPicker({
 *     api,
 *     entityType: 'customer',
 *     entityId: 5,
 *     onSaved: (locations) => { ... }
 *   }).render(container);
 *
 * یا برای مدیریت چند موقعیت یک entity:
 *   LocationPicker.openModal({
 *     api,
 *     entityType: 'employee',
 *     entityId: 12,
 *     entityName: 'احمد رضایی'
 *   });
 */

const LOCATION_TYPES = {
    office:    { label: 'دفتر', icon: '🏢', color: '#3b82f6' },
    warehouse: { label: 'انبار', icon: '🏭', color: '#f59e0b' },
    home:      { label: 'منزل', icon: '🏠', color: '#10b981' },
    site:      { label: 'محل پروژه', icon: '🏗️', color: '#ef4444' },
    meeting:   { label: 'محل ملاقات', icon: '📍', color: '#8b5cf6' },
    branch:    { label: 'شعبه', icon: '🏪', color: '#06b6d4' },
    factory:   { label: 'کارخانه', icon: '🏭', color: '#dc2626' },
    other:     { label: 'سایر', icon: '📍', color: '#64748b' },
};

export default class LocationPicker {

    constructor(props = {}) {
        this.api          = props.api;
        this.entityType   = props.entityType;
        this.entityId     = props.entityId;
        this.entityName   = props.entityName ?? '';
        this.onSaved      = props.onSaved   ?? (() => {});
        this.onChange     = props.onChange  ?? (() => {});

        this._locations   = [];
        this._map         = null;
        this._markers     = [];
        this._activePin   = null;
        this._container   = null;
    }

    /** ساخت modal از بیرون */
    static openModal(opts) {
        const ov = document.createElement('div');
        ov.className = 'acc-modal-overlay';
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:780px;max-height:92vh;overflow:hidden;display:flex;flex-direction:column;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">📍 موقعیت‌های ${LocationPicker._esc(opts.entityName || '')}</div>
            <div data-ref-picker style="flex:1;min-height:500px;"></div>
        </div>`;
        document.body.appendChild(ov);
        const close = () => ov.remove();
        ov.querySelector('.acc-modal__close').addEventListener('click', close);
        ov.addEventListener('click', e => { if (e.target === ov) close(); });

        const picker = new LocationPicker({ ...opts, onSaved: (locs) => { opts.onSaved?.(locs); } });
        picker.render(ov.querySelector('[data-ref-picker]'));
        return picker;
    }

    async render(container) {
        if (!container) return;
        this._container = container;
        container.innerHTML = `
        <div style="display:grid;grid-template-columns:280px 1fr;gap:12px;height:100%;min-height:450px;">

            <!-- لیست موقعیت‌ها -->
            <div style="display:flex;flex-direction:column;gap:8px;overflow-y:auto;">
                <button class="acc-btn acc-btn--primary acc-btn--sm" data-ref-pk="addBtn">➕ موقعیت جدید</button>
                <div data-ref-pk="list" style="display:flex;flex-direction:column;gap:6px;"></div>
            </div>

            <!-- نقشه -->
            <div data-ref-pk="map" style="border:1px solid #cbd5e1;border-radius:8px;min-height:450px;position:relative;background:#f8fafc;">
                <div data-ref-pk="loading" style="position:absolute;inset:0;display:flex;align-items:center;justify-content:center;color:#64748b;font-size:12px;">⏳ بارگذاری نقشه...</div>
            </div>
        </div>`;

        await this._loadLeaflet();
        this._initMap();
        await this._load();

        container.querySelector('[data-ref-pk="addBtn"]').addEventListener('click', () => this._openForm());
    }

    async _loadLeaflet() {
        if (window.L) return;
        const base = (window.ACC_CONFIG?.pluginUrl ?? '').replace(/\/+$/, '');
        const local = base ? `${base}/assets/vendor/leaflet` : '/wp-content/plugins/acc-engine/assets/vendor/leaflet';
        if (!document.querySelector('link[href*="leaflet"]')) {
            const l = document.createElement('link'); l.rel='stylesheet'; l.href=`${local}/leaflet.css`;
            document.head.appendChild(l);
        }
        if (!window.L) {
            await new Promise((res, rej) => {
                const s = document.createElement('script'); s.src=`${local}/leaflet.js`;
                s.onload=res; s.onerror=rej; document.head.appendChild(s);
            });
        }
    }

    _initMap() {
        const L = window.L;
        const el = this._container.querySelector('[data-ref-pk="map"]');
        const loadingEl = this._container.querySelector('[data-ref-pk="loading"]');
        loadingEl.style.display = 'none';

        this._map = L.map(el, { zoomControl: true }).setView([29.5926, 52.5836], 13);

        const base = (window.ACC_CONFIG?.pluginUrl ?? '').replace(/\/+$/, '');
        L.tileLayer(`${base || '/wp-content/plugins/acc-engine'}/assets/vendor/leaflet/tiles_esri/{z}/{x}/{y}.png`, {
            attribution: '© Esri', minZoom: 10, maxZoom: 19, maxNativeZoom: 16,
        }).addTo(this._map);

        // کلیک روی نقشه → افزودن موقعیت
        this._map.on('click', e => this._openForm(null, e.latlng.lat, e.latlng.lng));
    }

    async _load() {
        try {
            const res = await this.api.get('/gis/locations', {
                entity_type: this.entityType,
                entity_id:   this.entityId,
            });
            this._locations = res?.data ?? [];
            this._renderList();
            this._renderMarkers();
            this.onChange(this._locations);
        } catch (e) {
            this._container.querySelector('[data-ref-pk="list"]').innerHTML =
                `<div style="color:#ef4444;font-size:12px;padding:8px;">❌ خطا در بارگذاری</div>`;
        }
    }

    _renderList() {
        const list = this._container.querySelector('[data-ref-pk="list"]');
        if (!this._locations.length) {
            list.innerHTML = `
                <div style="color:#64748b;font-size:12px;padding:16px;text-align:center;background:#f8fafc;border-radius:8px;">
                    موقعیتی ثبت نشده.<br>
                    <small>روی نقشه کلیک کنید یا دکمه بالا را بزنید.</small>
                </div>`;
            return;
        }

        list.innerHTML = this._locations.map(loc => {
            const type = LOCATION_TYPES[loc.location_type] ?? LOCATION_TYPES.other;
            return `
            <div class="loc-item" data-loc-id="${loc.id}" style="border:1.5px solid ${loc.is_primary == 1 ? type.color : '#e2e8f0'};border-radius:8px;padding:8px 10px;cursor:pointer;background:#fff;">
                <div style="display:flex;justify-content:space-between;align-items:start;gap:4px;">
                    <div style="flex:1;min-width:0;">
                        <div style="font-size:12px;font-weight:700;color:${type.color};">
                            ${type.icon} ${LocationPicker._esc(loc.label || type.label)}
                            ${loc.is_primary == 1 ? '<span style="background:'+type.color+';color:#fff;border-radius:3px;padding:0 4px;font-size:10px;margin-right:3px;">اصلی</span>' : ''}
                        </div>
                        ${loc.address ? `<div style="font-size:11px;color:#64748b;margin-top:3px;line-height:1.4;">${LocationPicker._esc(loc.address)}</div>` : ''}
                        ${loc.parcel_code ? `<div style="font-size:10px;color:#3b82f6;margin-top:2px;">🔗 پارسل ${LocationPicker._esc(loc.parcel_code)}</div>` : ''}
                    </div>
                    <div style="display:flex;flex-direction:column;gap:2px;">
                        <button class="loc-edit" style="background:none;border:none;cursor:pointer;font-size:11px;">✏️</button>
                        <button class="loc-del" style="background:none;border:none;cursor:pointer;font-size:11px;color:#ef4444;">🗑️</button>
                    </div>
                </div>
            </div>`;
        }).join('');

        list.querySelectorAll('.loc-item').forEach(it => {
            const id = parseInt(it.dataset.locId);
            const loc = this._locations.find(l => l.id == id);
            it.addEventListener('click', e => {
                if (e.target.closest('.loc-edit') || e.target.closest('.loc-del')) return;
                this._focusOnMap(loc);
            });
            it.querySelector('.loc-edit').addEventListener('click', e => {
                e.stopPropagation(); this._openForm(loc);
            });
            it.querySelector('.loc-del').addEventListener('click', async e => {
                e.stopPropagation();
                if (!confirm('حذف این موقعیت؟')) return;
                try { await this.api.delete(`/gis/locations/${id}`); this._load(); }
                catch (err) { alert('خطا: ' + (err?.message ?? '')); }
            });
        });
    }

    _renderMarkers() {
        const L = window.L;
        this._markers.forEach(m => this._map.removeLayer(m));
        this._markers = [];

        const bounds = [];
        this._locations.forEach(loc => {
            if (!loc.lat || !loc.lng) return;
            const type = LOCATION_TYPES[loc.location_type] ?? LOCATION_TYPES.other;
            const lat = parseFloat(loc.lat), lng = parseFloat(loc.lng);
            const m = L.marker([lat, lng], {
                title: loc.label || type.label,
                icon: L.divIcon({
                    className: '',
                    iconSize: [28, 28],
                    html: `<div style="background:${type.color};color:#fff;border-radius:50%;width:28px;height:28px;display:flex;align-items:center;justify-content:center;border:2px solid #fff;box-shadow:0 2px 6px rgba(0,0,0,.3);font-size:14px;">${type.icon}</div>`,
                }),
            });
            m.bindTooltip(`<b>${LocationPicker._esc(loc.label || type.label)}</b>${loc.address ? '<br>'+LocationPicker._esc(loc.address) : ''}`, { direction: 'top' });
            m.on('click', () => this._openForm(loc));
            m.addTo(this._map);
            this._markers.push(m);
            bounds.push([lat, lng]);
        });

        if (bounds.length) this._map.fitBounds(bounds, { padding: [40, 40], maxZoom: 16 });
    }

    _focusOnMap(loc) {
        if (!loc?.lat || !loc?.lng) return;
        this._map.setView([parseFloat(loc.lat), parseFloat(loc.lng)], 17, { animate: true });
    }

    _openForm(loc = null, prefillLat = null, prefillLng = null) {
        const isEdit = !!loc;
        const typeOpts = Object.entries(LOCATION_TYPES).map(([k, v]) =>
            `<option value="${k}" ${loc?.location_type === k ? 'selected' : ''}>${v.icon} ${v.label}</option>`
        ).join('');

        const ov = document.createElement('div'); ov.className = 'acc-modal-overlay';
        ov.style.zIndex = '10000';
        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="acc-form-group"><label>برچسب</label>
                    <input name="label" value="${LocationPicker._esc(loc?.label ?? '')}" placeholder="مثلاً: دفتر مرکزی">
                </div>
                <div class="acc-form-group"><label>نوع</label>
                    <select name="location_type">${typeOpts}</select>
                </div>
                <div class="acc-form-group"><label>آدرس</label>
                    <textarea name="address" rows="2">${LocationPicker._esc(loc?.address ?? '')}</textarea>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>عرض (lat)</label>
                        <input name="lat" type="number" step="any" required value="${loc?.lat ?? prefillLat ?? ''}" dir="ltr">
                    </div>
                    <div class="acc-form-group"><label>طول (lng)</label>
                        <input name="lng" type="number" step="any" required value="${loc?.lng ?? prefillLng ?? ''}" dir="ltr">
                    </div>
                </div>
                <div class="acc-form-group"><label>اتصال به پارسل GIS (اختیاری)</label>
                    <input name="parcel_id" type="number" placeholder="ID پارسل" value="${loc?.parcel_id ?? ''}">
                    <small style="color:#94a3b8;font-size:11px;">اگر این موقعیت یک پارسل ثبت‌شده است، ID آن را وارد کن</small>
                </div>
                <label style="display:flex;gap:6px;align-items:center;font-size:13px;margin:10px 0;">
                    <input type="checkbox" name="is_primary" value="1" ${loc?.is_primary == 1 ? 'checked' : ''}> ⭐ موقعیت اصلی
                </label>
                <div class="acc-form-group"><label>یادداشت</label>
                    <input name="notes" value="${LocationPicker._esc(loc?.notes ?? '')}">
                </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());
            body.entity_type = this.entityType;
            body.entity_id   = this.entityId;
            body.is_primary  = body.is_primary ? 1 : 0;
            if (!body.parcel_id) delete body.parcel_id;

            const btn = ev.target.querySelector('[type=submit]');
            btn.disabled = true;
            try {
                if (isEdit) await this.api.put(`/gis/locations/${loc.id}`, body);
                else        await this.api.post('/gis/locations', body);
                close();
                await this._load();
                this.onSaved(this._locations);
            } catch (e) { alert('خطا: ' + (e?.message ?? '')); btn.disabled = false; }
        });
    }

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