/**
 * UnitsSection.js — موجودی واحدها (نمای پلان طبقات)
 */
import SectionBase from "../../accounting/SectionBase.js";

const STATUS_COLOR = {
    available:'#10b981', reserved:'#f59e0b',
    sold:'#3b82f6', transferred:'#6b7280', cancelled:'#ef4444',
};
const STATUS_LABEL = {
    available:'آزاد', reserved:'رزروشده',
    sold:'فروخته‌شده', transferred:'تحویل‌شده', cancelled:'لغوشده',
};
const TYPE_LABEL  = { residential:'مسکونی', commercial:'تجاری', office:'اداری', parking:'پارکینگ', storage:'انباری' };
const TYPE_ICON   = { residential:'🏠', commercial:'🏪', office:'🏢', parking:'🚗', storage:'📦' };
const VIEW_LABEL  = { north:'شمالی', south:'جنوبی', east:'شرقی', west:'غربی', corner:'گوشه', inner:'حیاطی' };

export default class UnitsSection extends SectionBase {

    constructor(props={}) {
        super(props);
        this._units    = [];
        this._projects = [];
        this._filter   = { project_id:'', status:'', type:'' };
    }

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

    async afterRender() {
        try {
            const res = await this.api.get('/pc/projects', { per_page:200 });
            this._projects = res?.data ?? [];
        } catch {}
        await this._render();
    }

    async _render() {
        const root = this.ref('root');
        const projOpts = `<option value="">همه پروژه‌ها</option>` +
            this._projects.map(p=>`<option value="${p.id}">${this.escape(p.name)}</option>`).join('');

        root.innerHTML = `
        <div class="unit-toolbar">
            <select class="event-type-filter" data-ref="projSel">${projOpts}</select>
            <select class="event-type-filter" data-ref="statusSel">
                <option value="">همه وضعیت‌ها</option>
                ${Object.entries(STATUS_LABEL).map(([k,v])=>`<option value="${k}">${v}</option>`).join('')}
            </select>
            <select class="event-type-filter" data-ref="typeSel">
                <option value="">همه انواع</option>
                ${Object.entries(TYPE_LABEL).map(([k,v])=>`<option value="${k}">${v}</option>`).join('')}
            </select>
            <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>
        <!-- KPI -->
        <div class="unit-kpi-row" data-ref="kpiRow"></div>
        <!-- پلان طبقات -->
        <div data-ref="floorPlan" class="unit-floor-plan"></div>`;

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

        this.on(this.ref('projSel'),   'change', ()=>{ this._filter.project_id=this.ref('projSel').value;   this._load(); });
        this.on(this.ref('statusSel'), 'change', ()=>{ this._filter.status=this.ref('statusSel').value;     this._load(); });
        this.on(this.ref('typeSel'),   'change', ()=>{ this._filter.type=this.ref('typeSel').value;         this._load(); });
        this.on(this.ref('refreshBtn'),'click',  ()=> this._load());
        this.on(this.ref('addBtn'),    'click',  ()=> this._openUnitModal());

        await this._load();
    }

    async _load() {
        this.ref('floorPlan').innerHTML = `<div class="acc-loading"><div class="acc-spinner"></div></div>`;
        const params = {};
        if (this._filter.project_id) params.project_id = this._filter.project_id;
        if (this._filter.status)     params.status      = this._filter.status;
        if (this._filter.type)       params.type        = this._filter.type;
        try {
            const res = await this.api.get('/units', params);
            this._units = res?.data ?? [];
            this._renderKPI();
            this._renderFloorPlan();
        } catch {
            this.ref('floorPlan').innerHTML = `<div class="acc-error">خطا در بارگذاری</div>`;
        }
    }

    _renderKPI() {
        const kpi   = this.ref('kpiRow');
        const total = this._units.length;
        const avail = this._units.filter(u=>u.status==='available').length;
        const resrv = this._units.filter(u=>u.status==='reserved').length;
        const sold  = this._units.filter(u=>u.status==='sold').length;
        const trans = this._units.filter(u=>u.status==='transferred').length;
        const fmt   = v => new Intl.NumberFormat('fa-IR').format(Math.round(v));
        const totalVal = this._units.reduce((s,u)=>s+parseFloat(u.base_price||0),0);
        const soldVal  = this._units.filter(u=>['sold','transferred'].includes(u.status))
                                    .reduce((s,u)=>s+parseFloat(u.base_price||0),0);

        kpi.innerHTML = `
        <div class="unit-kpi" style="border-top:3px solid #1e293b;">
            <div class="unit-kpi-label">کل واحدها</div>
            <div class="unit-kpi-value">${total}</div>
        </div>
        <div class="unit-kpi" style="border-top:3px solid #10b981;">
            <div class="unit-kpi-label">🟢 آزاد</div>
            <div class="unit-kpi-value" style="color:#10b981;">${avail}</div>
        </div>
        <div class="unit-kpi" style="border-top:3px solid #f59e0b;">
            <div class="unit-kpi-label">🟡 رزروشده</div>
            <div class="unit-kpi-value" style="color:#f59e0b;">${resrv}</div>
        </div>
        <div class="unit-kpi" style="border-top:3px solid #3b82f6;">
            <div class="unit-kpi-label">🔵 فروخته‌شده</div>
            <div class="unit-kpi-value" style="color:#3b82f6;">${sold+trans}</div>
        </div>
        <div class="unit-kpi" style="border-top:3px solid #8b5cf6;">
            <div class="unit-kpi-label">💰 ارزش فروخته‌شده</div>
            <div class="unit-kpi-value" style="color:#8b5cf6;font-size:14px;">${fmt(soldVal)}</div>
            <div class="unit-kpi-sub">از ${fmt(totalVal)} ریال</div>
        </div>`;
    }

    _renderFloorPlan() {
        const plan = this.ref('floorPlan');
        if (!this._units.length) {
            plan.innerHTML = `<div class="acc-empty" style="margin-top:40px;">واحدی ثبت نشده است.</div>`;
            return;
        }

        // گروه‌بندی بر اساس طبقه
        const byFloor = {};
        this._units.forEach(u => {
            const f = u.floor ?? 0;
            if (!byFloor[f]) byFloor[f] = [];
            byFloor[f].push(u);
        });
        const floors = Object.keys(byFloor).map(Number).sort((a,b)=>b-a);

        plan.innerHTML = '';
        floors.forEach(floor => {
            const units = byFloor[floor];
            const row = document.createElement('div');
            row.className = 'unit-floor';
            row.innerHTML = `
                <div class="unit-floor-label">
                    ${floor === 0 ? 'همکف' : floor === -1 ? 'زیرزمین' : `طبقه ${floor}`}
                    <span style="font-size:11px;color:#94a3b8;margin-right:6px;">${units.length} واحد</span>
                </div>
                <div class="unit-floor-cells">
                    ${units.map(u => {
                        const color = STATUS_COLOR[u.status]||'#94a3b8';
                        const icon  = TYPE_ICON[u.type]||'🏢';
                        const sold  = u.customer_name ? `<div class="unit-cell-buyer">👤 ${this.escape(u.customer_name)}</div>` : '';
                        return `
                        <div class="unit-cell" style="border-top:3px solid ${color};"
                             data-id="${u.id}" title="${STATUS_LABEL[u.status]||u.status}">
                            <div class="unit-cell-icon">${icon}</div>
                            <div class="unit-cell-num">${this.escape(u.unit_number)}</div>
                            ${u.area_sqm ? `<div class="unit-cell-area">${u.area_sqm} م²</div>` : ''}
                            <div class="unit-cell-status" style="color:${color};">${STATUS_LABEL[u.status]||u.status}</div>
                            ${sold}
                        </div>`;
                    }).join('')}
                </div>`;
            row.querySelectorAll('.unit-cell').forEach(cell => {
                const unit = this._units.find(u => String(u.id) === cell.dataset.id);
                if (unit) cell.addEventListener('click', () => this._openUnitDetail(unit));
            });
            plan.appendChild(row);
        });
    }

    /* ── پانل جزئیات واحد ───────────────────────────────────── */
    _openUnitDetail(unit) {
        const color = STATUS_COLOR[unit.status]||'#94a3b8';
        const fmt   = v => new Intl.NumberFormat('fa-IR').format(Math.round(Number(v||0)));
        const row   = (l,v) => v ? `<div class="gis-info-row"><span class="gis-info-label">${l}</span><span class="gis-info-value">${v}</span></div>` : '';

        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 style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px;">
                <div>
                    <div style="font-size:18px;font-weight:800;color:#1e293b;">
                        ${TYPE_ICON[unit.type]||'🏢'} واحد ${this.escape(unit.unit_number)}
                    </div>
                    <div style="font-size:12px;color:#64748b;">
                        ${unit.floor===0?'همکف':unit.floor===-1?'زیرزمین':'طبقه '+unit.floor}
                        ${unit.project_name ? ' — '+this.escape(unit.project_name) : ''}
                    </div>
                </div>
                <span style="background:${color};color:#fff;padding:4px 12px;border-radius:8px;font-size:12px;font-weight:700;">
                    ${STATUS_LABEL[unit.status]||unit.status}
                </span>
            </div>

            <div class="gis-info-divider">مشخصات</div>
            ${row('نوع', TYPE_LABEL[unit.type])}
            ${row('مساحت ناخالص', unit.area_sqm ? unit.area_sqm+' م²' : null)}
            ${row('مساحت مفید', unit.area_useful_sqm ? unit.area_useful_sqm+' م²' : null)}
            ${row('دید', VIEW_LABEL[unit.view_direction])}
            <div style="display:flex;gap:10px;margin:8px 0;font-size:12px;color:#64748b;">
                ${unit.has_parking=='1'?'<span>🚗 پارکینگ</span>':''}
                ${unit.has_storage=='1'?'<span>📦 انباری</span>':''}
                ${unit.has_balcony=='1'?'<span>🏠 بالکن</span>':''}
            </div>

            <div class="gis-info-divider">قیمت</div>
            ${row('قیمت پایه', unit.base_price ? fmt(unit.base_price)+' ریال' : null)}
            ${row('قیمت هر متر', unit.price_per_sqm ? fmt(unit.price_per_sqm)+' ریال' : null)}

            ${unit.customer_name ? `
            <div class="gis-info-divider">خریدار</div>
            <div style="background:#eff6ff;border-radius:8px;padding:10px 12px;">
                <div style="font-weight:700;">👤 ${this.escape(unit.customer_name)}</div>
                ${unit.customer_phone ? `<div style="font-size:12px;color:#64748b;">📞 ${unit.customer_phone}</div>` : ''}
            </div>` : ''}

            <div class="acc-modal__actions" style="margin-top:16px;">
                <button class="acc-btn acc-btn--secondary" data-action="edit">✏️ ویرایش واحد</button>
                ${unit.status==='available' ? `<button class="acc-btn acc-btn--success" data-action="sell">💰 رزرو/فروش</button>` : ''}
                ${['reserved','sold'].includes(unit.status) ? `<button class="acc-btn acc-btn--primary" data-action="view-sale">📋 مشاهده فروش</button>` : ''}
            </div>
        </div>`;
        document.body.appendChild(ov);
        const close = () => ov.remove();
        ov.querySelector('.acc-modal__close').addEventListener('click', close);
        ov.addEventListener('click', ev => { if(ev.target===ov) close(); });
        ov.querySelector('[data-action="edit"]')?.addEventListener('click', () => { close(); this._openUnitModal(unit); });
        ov.querySelector('[data-action="sell"]')?.addEventListener('click', () => { close(); this._openSaleModal(unit); });
    }

    /* ── مودال واحد جدید/ویرایش ─────────────────────────────── */
    _openUnitModal(unit = null) {
        const isEdit   = !!unit;
        const u        = unit || {};
        const projOpts = `<option value="">— بدون پروژه —</option>` +
            this._projects.map(p=>`<option value="${p.id}" ${u.project_id==p.id?'selected':''}>${this.escape(p.name)}</option>`).join('');
        const selT = k => u.type === k ? 'selected' : '';
        const selV = k => u.view_direction === k ? 'selected' : '';

        const ov = document.createElement('div'); ov.className = 'acc-modal-overlay';
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:500px;max-height:90vh;overflow-y:auto;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">🏢 ${isEdit?'ویرایش':'افزودن'} واحد</div>
            <form>
                <div class="acc-form-group"><label>پروژه</label>
                    <select name="project_id">${projOpts}</select>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>شماره واحد *</label>
                        <input name="unit_number" required value="${this.escape(u.unit_number||'')}">
                    </div>
                    <div class="acc-form-group"><label>طبقه *</label>
                        <input name="floor" type="number" value="${u.floor??'0'}" required>
                    </div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>بلوک/برج</label>
                        <input name="block" value="${this.escape(u.block||'')}">
                    </div>
                    <div class="acc-form-group"><label>نوع</label>
                        <select name="type">
                            <option value="residential" ${selT('residential')}>🏠 مسکونی</option>
                            <option value="commercial"  ${selT('commercial')}>🏪 تجاری</option>
                            <option value="office"      ${selT('office')}>🏢 اداری</option>
                            <option value="parking"     ${selT('parking')}>🚗 پارکینگ</option>
                            <option value="storage"     ${selT('storage')}>📦 انباری</option>
                        </select>
                    </div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>مساحت ناخالص (م²)</label>
                        <input name="area_sqm" type="number" step="0.1" value="${u.area_sqm||''}">
                    </div>
                    <div class="acc-form-group"><label>مساحت مفید (م²)</label>
                        <input name="area_useful_sqm" type="number" step="0.1" value="${u.area_useful_sqm||''}">
                    </div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>قیمت پایه (ریال)</label>
                        <input name="base_price" type="number" id="base-price-inp" value="${u.base_price||''}">
                    </div>
                    <div class="acc-form-group"><label>قیمت هر متر (ریال)</label>
                        <input name="price_per_sqm" type="number" id="psqm-inp" value="${u.price_per_sqm||''}">
                    </div>
                </div>
                <div class="acc-form-group"><label>دید</label>
                    <select name="view_direction">
                        <option value="">— بدون انتخاب —</option>
                        ${Object.entries(VIEW_LABEL).map(([k,v])=>`<option value="${k}" ${selV(k)}>${v}</option>`).join('')}
                    </select>
                </div>
                <div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:8px;margin:10px 0;">
                    <label style="font-size:13px;display:flex;gap:6px;align-items:center;">
                        <input type="checkbox" name="has_parking" value="1" ${u.has_parking=='1'?'checked':''}> 🚗 پارکینگ
                    </label>
                    <label style="font-size:13px;display:flex;gap:6px;align-items:center;">
                        <input type="checkbox" name="has_storage" value="1" ${u.has_storage=='1'?'checked':''}> 📦 انباری
                    </label>
                    <label style="font-size:13px;display:flex;gap:6px;align-items:center;">
                        <input type="checkbox" name="has_balcony" value="1" ${u.has_balcony=='1'?'checked':''}> 🏠 بالکن
                    </label>
                </div>
                <div class="acc-form-group"><label>یادداشت</label>
                    <textarea name="notes" rows="2">${this.escape(u.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(); });

        // محاسبه خودکار قیمت
        const bInp = ov.querySelector('[name="area_sqm"]');
        const psInp = ov.querySelector('[name="price_per_sqm"]');
        const bpInp = ov.querySelector('[name="base_price"]');
        const calc = () => {
            const a = parseFloat(bInp.value)||0;
            const p = parseFloat(psInp.value)||0;
            if (a > 0 && p > 0 && !bpInp.value) bpInp.value = Math.round(a*p);
        };
        psInp.addEventListener('input', calc);
        bInp.addEventListener('input', calc);

        ov.querySelector('form').addEventListener('submit', async ev => {
            ev.preventDefault();
            const body = Object.fromEntries(new FormData(ev.target).entries());
            ['has_parking','has_storage','has_balcony'].forEach(k=>{ body[k]=body[k]?1:0; });
            ['block','view_direction','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(`/units/${unit.id}`, body);
                else        await this.api.post('/units', body);
                close(); this._toast(isEdit?'✅ واحد به‌روز شد':'✅ واحد افزوده شد');
                await this._load();
            } catch(err) { alert('خطا: '+(err?.message||'')); btn.disabled=false; }
        });
    }

    /* ── مودال رزرو/فروش واحد ───────────────────────────────── */
    async _openSaleModal(unit) {
        // بارگذاری مشتریان
        let customers = [];
        try {
            const res = await this.api.get('/sale-customers');
            customers = res?.data ?? [];
        } catch {}

        const custOpts = `<option value="">— انتخاب مشتری —</option>` +
            customers.map(c=>`<option value="${c.id}">${this.escape(c.name)} ${c.phone?'— '+c.phone:''}</option>`).join('');
        const fmt = v => new Intl.NumberFormat('fa-IR').format(Math.round(Number(v||0)));

        const ov = document.createElement('div'); ov.className = 'acc-modal-overlay';
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:460px;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">💰 رزرو/فروش واحد ${this.escape(unit.unit_number)}</div>
            <div style="background:#f0fdf4;border-radius:8px;padding:8px 12px;font-size:12px;color:#166534;margin-bottom:14px;">
                ${TYPE_ICON[unit.type]||'🏢'} ${TYPE_LABEL[unit.type]} | طبقه ${unit.floor} |
                ${unit.area_sqm?unit.area_sqm+' م² |':''} قیمت پایه: ${fmt(unit.base_price)} ریال
            </div>
            <form>
                <div class="acc-form-group">
                    <label>مشتری *</label>
                    <select name="customer_id" required>${custOpts}</select>
                    <button type="button" class="acc-btn acc-btn--secondary acc-btn--sm" style="margin-top:6px;" data-action="new-customer">
                        ➕ مشتری جدید
                    </button>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>قیمت فروش (ریال) *</label>
                        <input name="sale_price" type="number" required value="${unit.base_price||''}">
                    </div>
                    <div class="acc-form-group"><label>نوع پرداخت</label>
                        <select name="payment_type">
                            <option value="installment">اقساطی</option>
                            <option value="cash">نقدی</option>
                            <option value="mixed">ترکیبی</option>
                        </select>
                    </div>
                </div>
                <div class="acc-form-group"><label>تاریخ رزرو</label>
                    <input name="reservation_date" type="date" value="${new Date().toISOString().split('T')[0]}">
                </div>
                <div class="acc-form-group"><label>یادداشت</label>
                    <textarea name="notes" rows="2"></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--success">✅ ثبت رزرو</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('[data-action="new-customer"]').addEventListener('click', () => {
            close(); this._openQuickCustomerModal(unit);
        });
        ov.querySelector('form').addEventListener('submit', async ev => {
            ev.preventDefault();
            const body = Object.fromEntries(new FormData(ev.target).entries());
            body.unit_id = unit.id;
            const btn = ev.target.querySelector('[type="submit"]');
            btn.disabled = true;
            try {
                await this.api.post('/sales', body);
                close(); this._toast('✅ رزرو ثبت شد', '#10b981');
                await this._load();
            } catch(err) { alert('خطا: '+(err?.message||'')); btn.disabled=false; }
        });
    }

    _openQuickCustomerModal(unit) {
        const ov = document.createElement('div'); ov.className = 'acc-modal-overlay';
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:380px;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">👤 مشتری جدید</div>
            <form>
                <div class="acc-form-group"><label>نام *</label><input name="name" required></div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>کد ملی</label><input name="national_id"></div>
                    <div class="acc-form-group"><label>تلفن</label><input name="phone" type="tel"></div>
                </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', 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 {
                await this.api.post('/sale-customers', body);
                close(); this._toast('✅ مشتری ثبت شد');
                this._openSaleModal(unit); // بازگشت به مودال فروش
            } catch(err) { alert('خطا: '+(err?.message||'')); btn.disabled=false; }
        });
    }

    _fmt(v) { return new Intl.NumberFormat('fa-IR').format(Math.round(Number(v??0))); }
    _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);
    }
}
