/**
 * TreasuryDashSection.js — داشبورد مالی پروژه
 * KPI | بودجه vs واقعی | جریان نقدی | P&L
 */
import SectionBase from "../../accounting/SectionBase.js";

const CAT_LABEL = {
    land:'خرید زمین', construction:'ساخت و ساز', permits:'مجوزها',
    design:'طراحی', marketing:'بازاریابی', finance_cost:'هزینه مالی',
    tax:'مالیات', sales_income:'درآمد فروش', investor:'آورده سرمایه‌گذار',
    loan:'تسهیلات', other:'سایر',
};
const CAT_ICON = {
    land:'📍', construction:'🏗️', permits:'📋', design:'✏️',
    marketing:'📢', finance_cost:'💸', tax:'🏛️',
    sales_income:'💰', investor:'🤝', loan:'🏦', other:'📌',
};
const CAT_COLOR = {
    land:'#ef4444', construction:'#f97316', permits:'#f59e0b', design:'#8b5cf6',
    marketing:'#ec4899', finance_cost:'#dc2626', tax:'#b45309',
    sales_income:'#10b981', investor:'#3b82f6', loan:'#6366f1', other:'#94a3b8',
};

export default class TreasuryDashSection extends SectionBase {

    constructor(props={}) {
        super(props);
        this._projects  = [];
        this._projectId = null;
        this._data      = null;
    }

    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 opts = `<option value="">— انتخاب پروژه —</option>` +
            this._projects.map(p=>`<option value="${p.id}" ${this._projectId==p.id?'selected':''}>${this.escape(p.name)}</option>`).join('');

        root.innerHTML = `
        <div style="display:flex;gap:10px;align-items:center;margin-bottom:20px;flex-wrap:wrap;">
            <select class="event-type-filter" data-ref="projSel" style="flex:1;max-width:320px;">${opts}</select>
            <button class="acc-btn acc-btn--secondary acc-btn--sm" data-ref="budgetBtn" style="display:none;">
                🎯 تعریف بودجه
            </button>
            <button class="acc-btn acc-btn--primary acc-btn--sm" data-ref="addEntryBtn" style="display:none;">
                ➕ ثبت تراکنش
            </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('projSel'),   'change', ()=>{ this._projectId=this.ref('projSel').value; this._load(); });
        this.on(this.ref('refreshBtn'),'click',  ()=>this._load());
        this.on(this.ref('addEntryBtn'),'click', ()=>this._openEntryModal());
        this.on(this.ref('budgetBtn'),  'click', ()=>this._openBudgetModal());

        if (this._projectId) await this._load();
        else this.ref('body').innerHTML = `<div class="treasury-empty">📊 یک پروژه انتخاب کنید تا داشبورد مالی آن نمایش داده شود.</div>`;
    }

    async _load() {
        if (!this._projectId) return;
        this.ref('body').innerHTML = `<div class="acc-loading"><div class="acc-spinner"></div></div>`;
        this.ref('budgetBtn').style.display   = '';
        this.ref('addEntryBtn').style.display = '';
        try {
            const res = await this.api.get(`/treasury/project/${this._projectId}/dashboard`);
            this._data = res;
            this._renderDash(res);
        } catch {
            this.ref('body').innerHTML = `<div class="acc-error">خطا در بارگذاری</div>`;
        }
    }

    _renderDash(d) {
        const body = this.ref('body');
        const fmt  = v => new Intl.NumberFormat('fa-IR').format(Math.round(Number(v||0)));
        const s    = d.summary || {};
        const u    = d.units   || {};

        const netColor = s.net_profit >= 0 ? '#10b981' : '#ef4444';
        const netLabel = s.net_profit >= 0 ? '✅ سود' : '❌ زیان';

        // ── KPI اصلی ───────────────────────────────────────
        const kpiHtml = `
        <div class="treasury-kpi-grid">
            <div class="treasury-kpi treasury-kpi--expense">
                <div class="treasury-kpi-icon">💸</div>
                <div class="treasury-kpi-label">مجموع هزینه</div>
                <div class="treasury-kpi-value">${fmt(s.total_expense)}</div>
                <div class="treasury-kpi-sub">ریال</div>
            </div>
            <div class="treasury-kpi treasury-kpi--income">
                <div class="treasury-kpi-icon">💰</div>
                <div class="treasury-kpi-label">مجموع درآمد</div>
                <div class="treasury-kpi-value">${fmt(s.total_income)}</div>
                <div class="treasury-kpi-sub">ریال</div>
            </div>
            <div class="treasury-kpi" style="border-top:3px solid ${netColor};">
                <div class="treasury-kpi-icon">${s.net_profit>=0?'📈':'📉'}</div>
                <div class="treasury-kpi-label">${netLabel}</div>
                <div class="treasury-kpi-value" style="color:${netColor};">${fmt(Math.abs(s.net_profit))}</div>
                <div class="treasury-kpi-sub">${s.net_pct}٪ از درآمد — ریال</div>
            </div>
            <div class="treasury-kpi" style="border-top:3px solid #8b5cf6;">
                <div class="treasury-kpi-icon">🎯</div>
                <div class="treasury-kpi-label">پیش‌بینی درآمد</div>
                <div class="treasury-kpi-value" style="color:#8b5cf6;">${fmt(s.sales_forecast)}</div>
                <div class="treasury-kpi-sub">${fmt(s.sales_revenue)} دریافتی — ریال</div>
            </div>
        </div>`;

        // ── بودجه در مقابل واقعی ─────────────────────────
        const budgetHtml = s.budget > 0 ? `
        <div class="treasury-card" style="margin-bottom:16px;">
            <div class="treasury-card-title">🎯 بودجه در مقابل هزینه واقعی</div>
            <div style="display:flex;justify-content:space-between;font-size:12px;color:#64748b;margin-bottom:6px;">
                <span>هزینه: ${fmt(s.total_expense)} ریال</span>
                <span>بودجه: ${fmt(s.budget)} ریال</span>
            </div>
            <div class="treasury-bar-track">
                <div class="treasury-bar-fill ${s.budget_used_pct>100?'treasury-bar-fill--over':s.budget_used_pct>80?'treasury-bar-fill--warn':''}"
                     style="width:${Math.min(s.budget_used_pct,100)}%"></div>
            </div>
            <div style="font-size:12px;margin-top:4px;${s.budget_used_pct>100?'color:#ef4444;':'color:#64748b;'}">
                ${s.budget_used_pct}٪ از بودجه مصرف‌شده
                ${s.budget_used_pct>100?'⚠️ از بودجه فراتر رفته':''}
            </div>
        </div>` : '';

        // ── واحدهای پروژه ─────────────────────────────────
        const unitsHtml = u.total > 0 ? `
        <div class="treasury-card" style="margin-bottom:16px;">
            <div class="treasury-card-title">🏢 وضعیت فروش واحدها</div>
            <div style="display:flex;gap:16px;align-items:center;flex-wrap:wrap;">
                <div style="flex:1;">
                    <div style="display:flex;justify-content:space-between;font-size:12px;color:#64748b;margin-bottom:4px;">
                        <span>فروش: ${u.sold} واحد از ${u.total}</span>
                        <span>${u.sell_pct}٪</span>
                    </div>
                    <div class="treasury-bar-track">
                        <div class="treasury-bar-fill" style="width:${u.sell_pct}%;background:#10b981;"></div>
                    </div>
                </div>
                <div style="display:flex;gap:12px;font-size:11px;">
                    <span style="color:#10b981;">🟢 آزاد: ${u.available}</span>
                    <span style="color:#f59e0b;">🟡 رزرو: ${u.reserved}</span>
                    <span style="color:#3b82f6;">🔵 فروش: ${u.sold}</span>
                </div>
            </div>
            <div style="font-size:12px;color:#64748b;margin-top:8px;">
                ارزش فروخته‌شده: <b style="color:#10b981;">${fmt(u.sold_value)} ریال</b>
                از کل <b>${fmt(u.total_value)} ریال</b>
            </div>
        </div>` : '';

        // ── تفکیک هزینه بر اساس دسته‌بندی ────────────────
        const expCats  = d.expense_by_cat || {};
        const totalExp = s.total_expense || 1;
        const expBars  = Object.entries(expCats)
            .sort((a,b)=>b[1]-a[1])
            .map(([cat,amount]) => {
                const pct = Math.round(amount/totalExp*100);
                const bud = (d.budget_by_cat||{})[cat];
                return `
                <div style="margin-bottom:10px;">
                    <div style="display:flex;justify-content:space-between;font-size:12px;margin-bottom:3px;">
                        <span>${CAT_ICON[cat]||'📌'} ${CAT_LABEL[cat]||cat}</span>
                        <span style="color:#64748b;">${fmt(amount)} ریال (${pct}٪)</span>
                    </div>
                    <div class="treasury-bar-track">
                        <div style="height:100%;border-radius:4px;background:${CAT_COLOR[cat]||'#94a3b8'};width:${pct}%;transition:width .4s;"></div>
                    </div>
                    ${bud ? `<div style="font-size:10px;color:#94a3b8;margin-top:2px;">
                        بودجه: ${fmt(bud)} ریال ${amount>bud?'<span style="color:#ef4444;">⚠️ فراتر از بودجه</span>':''}
                    </div>` : ''}
                </div>`;
            }).join('') || '<div class="gis-empty-tab">هنوز هزینه‌ای ثبت نشده.</div>';

        // ── آخرین تراکنش‌ها ─────────────────────────────
        const recentHtml = (d.recent||[]).length ? `
        <div class="treasury-card">
            <div class="treasury-card-title">🕒 آخرین تراکنش‌ها</div>
            ${(d.recent||[]).map(e=>{
                const isIn = e.direction==='in';
                return `
                <div class="treasury-entry-row">
                    <div style="font-size:11px;color:#94a3b8;">${e.entry_date}</div>
                    <div style="flex:1;font-size:13px;">${this.escape(e.description)}</div>
                    <div style="font-size:11px;color:#64748b;">${CAT_LABEL[e.category]||e.category}</div>
                    <div style="font-weight:700;font-size:13px;color:${isIn?'#10b981':'#ef4444'};">
                        ${isIn?'▲':'▼'} ${fmt(e.amount)}
                    </div>
                </div>`;
            }).join('')}
        </div>` : '';

        // ── گزارش ماهانه ─────────────────────────────────
        const months = {};
        (d.monthly||[]).forEach(m=>{
            if (!months[m.month]) months[m.month]={in:0,out:0};
            months[m.month][m.direction] += parseFloat(m.total);
        });
        const maxVal = Math.max(...Object.values(months).map(m=>Math.max(m.in,m.out)), 1);
        const monthHtml = Object.keys(months).length > 0 ? `
        <div class="treasury-card" style="margin-bottom:16px;">
            <div class="treasury-card-title">📅 جریان نقدی ۶ ماه اخیر</div>
            <div class="treasury-monthly-chart">
                ${Object.entries(months).map(([month,mv])=>`
                <div class="treasury-month-col">
                    <div style="display:flex;gap:3px;align-items:flex-end;height:80px;">
                        <div style="width:16px;background:#10b981;border-radius:3px 3px 0 0;
                             height:${Math.round(mv.in/maxVal*80)}px;" title="درآمد: ${fmt(mv.in)}"></div>
                        <div style="width:16px;background:#ef4444;border-radius:3px 3px 0 0;
                             height:${Math.round(mv.out/maxVal*80)}px;" title="هزینه: ${fmt(mv.out)}"></div>
                    </div>
                    <div style="font-size:9px;color:#94a3b8;margin-top:4px;text-align:center;">${month.slice(5)}</div>
                </div>`).join('')}
            </div>
            <div style="display:flex;gap:12px;font-size:11px;margin-top:6px;">
                <span><span style="color:#10b981;">■</span> درآمد</span>
                <span><span style="color:#ef4444;">■</span> هزینه</span>
            </div>
        </div>` : '';

        body.innerHTML = `
        ${kpiHtml}
        <div class="treasury-two-col">
            <div>
                ${budgetHtml}
                ${unitsHtml}
                ${monthHtml}
            </div>
            <div>
                <div class="treasury-card">
                    <div class="treasury-card-title">💸 تفکیک هزینه</div>
                    ${expBars}
                </div>
            </div>
        </div>
        ${recentHtml}`;
    }

    /* ── مودال ثبت تراکنش ───────────────────────────────────── */
    _openEntryModal(entry=null) {
        const isEdit = !!entry;
        const e = entry||{};
        const inCats  = ['sales_income','investor','loan','other'];
        const outCats = ['land','construction','permits','design','marketing','finance_cost','tax','other'];
        const allCats = [...new Set([...inCats,...outCats])];

        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">💰 ${isEdit?'ویرایش':'ثبت'} تراکنش</div>
            <form>
                <div style="display:flex;gap:12px;margin-bottom:14px;">
                    <label class="treasury-dir-opt treasury-dir-opt--out ${e.direction!=='in'?'treasury-dir-opt--active':''}">
                        <input type="radio" name="direction" value="out" ${e.direction!=='in'?'checked':''}> 💸 هزینه
                    </label>
                    <label class="treasury-dir-opt treasury-dir-opt--in ${e.direction==='in'?'treasury-dir-opt--active':''}">
                        <input type="radio" name="direction" value="in" ${e.direction==='in'?'checked':''}> 💰 درآمد
                    </label>
                </div>
                <div class="acc-form-group"><label>دسته‌بندی</label>
                    <select name="category">
                        ${allCats.map(k=>`<option value="${k}" ${e.category===k?'selected':''}>${CAT_ICON[k]||''} ${CAT_LABEL[k]||k}</option>`).join('')}
                    </select>
                </div>
                <div class="acc-form-group"><label>شرح *</label>
                    <input name="description" required value="${this.escape(e.description||'')}">
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>مبلغ (ریال) *</label>
                        <input name="amount" type="number" min="0" required value="${e.amount||''}">
                    </div>
                    <div class="acc-form-group"><label>تاریخ</label>
                        <input name="entry_date" type="date" value="${e.entry_date||new Date().toISOString().split('T')[0]}">
                    </div>
                </div>
                <div class="acc-form-group"><label>یادداشت</label>
                    <textarea name="notes" rows="2">${this.escape(e.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);

        // style radio buttons
        ov.querySelectorAll('input[name="direction"]').forEach(r=>{
            r.addEventListener('change', ()=>{
                ov.querySelectorAll('.treasury-dir-opt').forEach(el=>el.classList.remove('treasury-dir-opt--active'));
                r.closest('.treasury-dir-opt').classList.add('treasury-dir-opt--active');
            });
        });

        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.project_id = this._projectId;
            const btn = ev.target.querySelector('[type="submit"]');
            btn.disabled=true;
            try {
                if (isEdit) await this.api.put(`/treasury/entries/${e.id}`,body);
                else        await this.api.post('/treasury/entries',body);
                close(); this._toast('✅ ثبت شد'); this._load();
            } catch(err) { alert('خطا: '+(err?.message||'')); btn.disabled=false; }
        });
    }

    /* ── مودال بودجه تفصیلی ─────────────────────────────────── */
    _openBudgetModal() {
        const outCats = ['land','construction','permits','design','marketing','finance_cost','tax','other'];
        const existing = this._data?.budget_by_cat || {};

        const ov = document.createElement('div'); ov.className='acc-modal-overlay';
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:480px;max-height:90vh;overflow-y:auto;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">🎯 بودجه تفصیلی</div>
            <form>
                ${outCats.map(k=>`
                <div class="doc-form-row" style="align-items:center;">
                    <label style="flex:1;font-size:13px;">${CAT_ICON[k]||''} ${CAT_LABEL[k]||k}</label>
                    <div class="acc-form-group" style="flex:2;margin-bottom:8px;">
                        <input name="cat_${k}" type="number" min="0"
                            value="${existing[k]||''}" placeholder="ریال (اختیاری)">
                    </div>
                </div>`).join('')}
                <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 fd = new FormData(ev.target);
            const items = outCats
                .filter(k=>fd.get('cat_'+k))
                .map(k=>({category:k, label:CAT_LABEL[k], planned_amount:parseFloat(fd.get('cat_'+k))||0}));
            const btn = ev.target.querySelector('[type="submit"]');
            btn.disabled=true;
            try {
                await this.api.post(`/treasury/budget/${this._projectId}`,{items});
                close(); this._toast('✅ بودجه ذخیره شد'); this._load();
            } 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);
    }
}
