/**
 * SalesSection.js — پیگیری فروش‌ها
 * Pipeline: رزرو → قرارداد → تحویل
 */
import SectionBase from "../../accounting/SectionBase.js";

const STATUS_COLOR = { reserved:'#f59e0b', active:'#3b82f6', completed:'#10b981', cancelled:'#ef4444' };
const STATUS_LABEL = { reserved:'رزروشده', active:'قرارداد‌شده', completed:'تحویل‌شده', cancelled:'لغوشده' };
const PAY_LABEL    = { cash:'نقدی', installment:'اقساطی', mixed:'ترکیبی' };
const TYPE_LABEL   = { residential:'مسکونی', commercial:'تجاری', office:'اداری', parking:'پارکینگ', storage:'انباری' };

export default class SalesSection extends SectionBase {

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

    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 style="display:flex;gap:10px;align-items:center;margin-bottom:16px;flex-wrap:wrap;">
            <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>
            <button class="acc-btn acc-btn--secondary acc-btn--sm" data-ref="refreshBtn">🔄</button>
            <span data-ref="countLbl" style="font-size:12px;color:#94a3b8;"></span>
        </div>
        <!-- Kanban Pipeline -->
        <div class="sales-pipeline" data-ref="pipeline"></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('refreshBtn'),'click',  ()=>this._load());

        await this._load();
    }

    async _load() {
        this.ref('pipeline').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;
        try {
            const res = await this.api.get('/sales', params);
            this._sales = res?.data ?? [];
            this.ref('countLbl').textContent = `${this._sales.length} فروش`;
            this._renderPipeline();
        } catch {
            this.ref('pipeline').innerHTML = `<div class="acc-error">خطا</div>`;
        }
    }

    _renderPipeline() {
        const pipe  = this.ref('pipeline');
        const fmt   = v => new Intl.NumberFormat('fa-IR').format(Math.round(Number(v||0)));
        const cols  = [
            { key:'reserved',  label:'🟡 رزروشده' },
            { key:'active',    label:'🔵 قرارداد‌شده' },
            { key:'completed', label:'✅ تحویل‌شده' },
        ];

        if (!this._sales.length) {
            pipe.innerHTML = `<div class="acc-empty">فروشی ثبت نشده است.</div>`;
            return;
        }

        const activeFilter = this._filter.status;

        if (activeFilter) {
            // نمایش لیست ساده در حالت فیلتر
            pipe.innerHTML = `<div class="sales-list">${this._sales.map(s=>this._saleCard(s,fmt)).join('')}</div>`;
        } else {
            // نمایش Kanban
            pipe.innerHTML = `
            <div class="sales-kanban">
                ${cols.map(col => {
                    const items = this._sales.filter(s=>s.status===col.key);
                    const total = items.reduce((sum,s)=>sum+parseFloat(s.sale_price||0),0);
                    return `
                    <div class="sales-kanban-col">
                        <div class="sales-kanban-header" style="border-top:3px solid ${STATUS_COLOR[col.key]}">
                            <span>${col.label}</span>
                            <span class="sales-kanban-count">${items.length}</span>
                        </div>
                        <div style="font-size:11px;color:#64748b;margin-bottom:8px;">${fmt(total)} ریال</div>
                        <div class="sales-kanban-body">
                            ${items.map(s=>this._saleCard(s,fmt)).join('') || '<div class="gis-empty-tab">—</div>'}
                        </div>
                    </div>`;
                }).join('')}
            </div>`;
        }

        pipe.querySelectorAll('[data-sale-id]').forEach(el => {
            const sale = this._sales.find(s=>String(s.id)===el.dataset.saleId);
            if (sale) el.addEventListener('click', ()=>this._openSaleDetail(sale));
        });
    }

    _saleCard(s, fmt) {
        const color = STATUS_COLOR[s.status]||'#94a3b8';
        const pct   = s.sale_price > 0 ? Math.round(s.paid_amount/s.sale_price*100) : 0;
        return `
        <div class="sale-card" data-sale-id="${s.id}" style="border-right:3px solid ${color};cursor:pointer;">
            <div style="display:flex;justify-content:space-between;align-items:start;">
                <div>
                    <div style="font-weight:700;font-size:13px;">واحد ${this.escape(s.unit_number)}</div>
                    <div style="font-size:11px;color:#64748b;">
                        ${s.project_name?this.escape(s.project_name)+' | ':''}
                        طبقه ${s.floor} | ${TYPE_LABEL[s.unit_type]||s.unit_type}
                    </div>
                </div>
                <span style="font-size:10px;color:${color};font-weight:700;">${STATUS_LABEL[s.status]}</span>
            </div>
            <div style="font-size:12px;margin-top:6px;">
                👤 ${s.customer_name ? this.escape(s.customer_name) : '—'}
            </div>
            <div style="font-weight:700;font-size:13px;margin-top:4px;">${fmt(s.sale_price)} ریال</div>
            ${s.sale_price > 0 ? `
            <div class="contract-progress-bar" style="margin-top:6px;">
                <div class="contract-progress-fill" style="width:${pct}%;background:${color}"></div>
            </div>
            <div style="font-size:10px;color:#94a3b8;margin-top:2px;">${pct}٪ پرداخت‌شده</div>` : ''}
        </div>`;
    }

    _openSaleDetail(sale) {
        const fmt   = v => new Intl.NumberFormat('fa-IR').format(Math.round(Number(v||0)));
        const color = STATUS_COLOR[sale.status]||'#94a3b8';
        const pct   = sale.sale_price > 0 ? Math.round(parseFloat(sale.paid_amount||0)/parseFloat(sale.sale_price)*100) : 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 style="display:flex;justify-content:space-between;align-items:center;margin-bottom:14px;">
                <div>
                    <div style="font-size:16px;font-weight:800;">واحد ${this.escape(sale.unit_number)} — طبقه ${sale.floor}</div>
                    <div style="font-size:12px;color:#64748b;">${sale.project_name||''}</div>
                </div>
                <span style="background:${color};color:#fff;padding:4px 10px;border-radius:8px;font-size:11px;font-weight:700;">
                    ${STATUS_LABEL[sale.status]}
                </span>
            </div>

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

            <div class="gis-info-divider">مالی</div>
            <div class="gis-info-row"><span class="gis-info-label">قیمت فروش</span><span class="gis-info-value">${fmt(sale.sale_price)} ریال</span></div>
            <div class="gis-info-row"><span class="gis-info-label">پرداخت‌شده</span><span class="gis-info-value" style="color:#10b981;">${fmt(sale.paid_amount||0)} ریال</span></div>
            <div class="gis-info-row"><span class="gis-info-label">مانده</span><span class="gis-info-value" style="color:#ef4444;">${fmt(parseFloat(sale.sale_price)-parseFloat(sale.paid_amount||0))} ریال</span></div>
            <div class="contract-progress-bar"><div class="contract-progress-fill" style="width:${pct}%;background:${color}"></div></div>

            <div class="gis-info-divider">تاریخ‌ها</div>
            ${sale.reservation_date   ? `<div class="gis-info-row"><span class="gis-info-label">رزرو</span><span class="gis-info-value">${sale.reservation_date}</span></div>` : ''}
            ${sale.sale_contract_date ? `<div class="gis-info-row"><span class="gis-info-label">قرارداد</span><span class="gis-info-value">${sale.sale_contract_date}</span></div>` : ''}
            ${sale.transfer_date      ? `<div class="gis-info-row"><span class="gis-info-label">تحویل</span><span class="gis-info-value">${sale.transfer_date}</span></div>` : ''}

            <div class="acc-modal__actions" style="margin-top:16px;flex-wrap:wrap;gap:8px;">
                ${sale.status==='reserved' ? `<button class="acc-btn acc-btn--primary" data-action="activate">📋 ثبت قرارداد</button>` : ''}
                ${sale.status==='active'   ? `<button class="acc-btn acc-btn--success" data-action="transfer">🏠 تحویل واحد</button>` : ''}
                ${sale.status!=='completed' && sale.status!=='cancelled' ? `<button class="acc-btn acc-btn--danger" data-action="cancel">❌ لغو فروش</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="activate"]')?.addEventListener('click', async () => {
            const date = prompt('تاریخ انعقاد قرارداد (YYYY-MM-DD):', new Date().toISOString().split('T')[0]);
            if (!date) return;
            await this.api.put(`/sales/${sale.id}`, { status:'active', sale_contract_date: date });
            close(); this._toast('✅ قرارداد ثبت شد', '#3b82f6'); this._load();
        });
        ov.querySelector('[data-action="transfer"]')?.addEventListener('click', async () => {
            const date = prompt('تاریخ تحویل (YYYY-MM-DD):', new Date().toISOString().split('T')[0]);
            if (!date) return;
            await this.api.post(`/sales/${sale.id}/transfer`, { transfer_date: date });
            close(); this._toast('✅ تحویل واحد ثبت شد', '#10b981'); this._load();
        });
        ov.querySelector('[data-action="cancel"]')?.addEventListener('click', async () => {
            if (!confirm('لغو این فروش؟')) return;
            await this.api.delete(`/sales/${sale.id}`);
            close(); this._toast('❌ فروش لغو شد', '#ef4444'); this._load();
        });
    }

    _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);
    }
}
