/**
 * TreasuryLedgerSection.js — دفتر نقدی (همه تراکنش‌ها)
 */
import SectionBase from "../../accounting/SectionBase.js";

const CAT_LABEL = {
    land:'خرید زمین', construction:'ساخت و ساز', permits:'مجوزها',
    design:'طراحی', marketing:'بازاریابی', finance_cost:'هزینه مالی',
    tax:'مالیات', sales_income:'درآمد فروش', investor:'سرمایه‌گذار',
    loan:'تسهیلات', other:'سایر',
};

export default class TreasuryLedgerSection extends SectionBase {

    constructor(props={}) {
        super(props);
        this._entries  = [];
        this._projects = [];
        this._filter   = { project_id:'', direction:'', from:'', to:'' };
    }

    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:8px;align-items:center;margin-bottom:14px;flex-wrap:wrap;">
            <select class="event-type-filter" data-ref="projSel">${projOpts}</select>
            <select class="event-type-filter" data-ref="dirSel">
                <option value="">هر دو</option>
                <option value="in">💰 درآمد</option>
                <option value="out">💸 هزینه</option>
            </select>
            <input type="date" class="acc-input" data-ref="fromInp" style="width:130px;" title="از تاریخ">
            <input type="date" class="acc-input" data-ref="toInp"   style="width:130px;" title="تا تاریخ">
            <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>
            <span data-ref="totalLbl" style="font-size:12px;color:#94a3b8;"></span>
        </div>
        <div data-ref="tableWrap"></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('dirSel'),  'change', ()=>{ this._filter.direction=this.ref('dirSel').value;   this._load(); });
        this.on(this.ref('fromInp'), 'change', ()=>{ this._filter.from=this.ref('fromInp').value;       this._load(); });
        this.on(this.ref('toInp'),   'change', ()=>{ this._filter.to=this.ref('toInp').value;           this._load(); });
        this.on(this.ref('refreshBtn'),'click',()=>this._load());
        this.on(this.ref('addBtn'),    'click', ()=>this._openEntryModal());
        await this._load();
    }

    async _load() {
        this.ref('tableWrap').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.direction)  params.direction   = this._filter.direction;
        if (this._filter.from)       params.from        = this._filter.from;
        if (this._filter.to)         params.to          = this._filter.to;
        try {
            const res = await this.api.get('/treasury/entries',params);
            this._entries = res?.data??[];
            this._renderTable();
        } catch {
            this.ref('tableWrap').innerHTML = `<div class="acc-error">خطا</div>`;
        }
    }

    _renderTable() {
        const wrap = this.ref('tableWrap');
        const fmt  = v=>new Intl.NumberFormat('fa-IR').format(Math.round(Number(v||0)));
        if (!this._entries.length) {
            wrap.innerHTML = `<div class="acc-empty">تراکنشی ثبت نشده.</div>`;
            this.ref('totalLbl').textContent='';
            return;
        }

        const totalIn  = this._entries.filter(e=>e.direction==='in').reduce((s,e)=>s+parseFloat(e.amount),0);
        const totalOut = this._entries.filter(e=>e.direction==='out').reduce((s,e)=>s+parseFloat(e.amount),0);
        this.ref('totalLbl').innerHTML =
            `<span style="color:#10b981;">▲${fmt(totalIn)}</span> &nbsp;
             <span style="color:#ef4444;">▼${fmt(totalOut)}</span> &nbsp;
             <b>${totalIn-totalOut>=0?'سود':'زیان'}: ${fmt(Math.abs(totalIn-totalOut))}</b>`;

        wrap.innerHTML = `
        <div class="treasury-ledger">
            <div class="treasury-ledger-header">
                <span>تاریخ</span>
                <span>شرح</span>
                <span>دسته</span>
                <span>پروژه</span>
                <span>درآمد</span>
                <span>هزینه</span>
                <span>موجودی</span>
                <span></span>
            </div>
            ${this._entries.map(e=>{
                const isIn = e.direction==='in';
                const bal  = parseFloat(e.running_balance||0);
                return `
                <div class="treasury-ledger-row ${isIn?'treasury-ledger-row--in':'treasury-ledger-row--out'}"
                     data-id="${e.id}">
                    <span class="treasury-cell-date">${e.entry_date}</span>
                    <span class="treasury-cell-desc">${this.escape(e.description)}</span>
                    <span class="treasury-cell-cat">${CAT_LABEL[e.category]||e.category}</span>
                    <span class="treasury-cell-proj">${this.escape(e.project_name||'—')}</span>
                    <span class="treasury-cell-in">${isIn?'<b style="color:#10b981;">'+fmt(e.amount)+'</b>':'—'}</span>
                    <span class="treasury-cell-out">${!isIn?'<b style="color:#ef4444;">'+fmt(e.amount)+'</b>':'—'}</span>
                    <span class="treasury-cell-bal" style="color:${bal>=0?'#10b981':'#ef4444'};font-weight:700;">
                        ${fmt(bal)}
                    </span>
                    <span style="display:flex;gap:4px;">
                        ${e.source==='manual'?`
                        <button class="gis-btn gis-btn--xs" data-edit="${e.id}">✏️</button>
                        <button class="gis-btn gis-btn--xs gis-btn--danger" data-del="${e.id}">🗑️</button>
                        `:' '}
                    </span>
                </div>`;
            }).join('')}
        </div>`;

        wrap.querySelectorAll('[data-edit]').forEach(btn=>{
            const entry = this._entries.find(e=>String(e.id)===btn.dataset.edit);
            if (entry) btn.addEventListener('click',()=>this._openEntryModal(entry));
        });
        wrap.querySelectorAll('[data-del]').forEach(btn=>{
            btn.addEventListener('click',async()=>{
                if (!confirm('حذف این تراکنش؟')) return;
                try {
                    await this.api.delete(`/treasury/entries/${btn.dataset.del}`);
                    this._toast('🗑️ حذف شد'); this._load();
                } catch(err){ alert('خطا: '+(err?.message||'')); }
            });
        });
    }

    _openEntryModal(entry=null) {
        const isEdit = !!entry;
        const e = entry||{};
        const projOpts = `<option value="">— انتخاب پروژه —</option>` +
            this._projects.map(p=>`<option value="${p.id}" ${e.project_id==p.id||this._filter.project_id==p.id?'selected':''}>${this.escape(p.name)}</option>`).join('');
        const cats = ['land','construction','permits','design','marketing','finance_cost','tax','sales_income','investor','loan','other'];

        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 class="acc-form-group"><label>پروژه *</label>
                    <select name="project_id" required>${projOpts}</select>
                </div>
                <div style="display:flex;gap:10px;margin-bottom:12px;">
                    <label style="font-size:13px;display:flex;gap:6px;align-items:center;background:#fef2f2;padding:8px 14px;border-radius:8px;cursor:pointer;flex:1;justify-content:center;border:2px solid ${e.direction!=='in'?'#ef4444':'#e2e8f0'}">
                        <input type="radio" name="direction" value="out" ${e.direction!=='in'?'checked':''}> 💸 هزینه
                    </label>
                    <label style="font-size:13px;display:flex;gap:6px;align-items:center;background:#f0fdf4;padding:8px 14px;border-radius:8px;cursor:pointer;flex:1;justify-content:center;border:2px solid ${e.direction==='in'?'#10b981':'#e2e8f0'}">
                        <input type="radio" name="direction" value="in" ${e.direction==='in'?'checked':''}> 💰 درآمد
                    </label>
                </div>
                <div class="acc-form-group"><label>دسته‌بندی</label>
                    <select name="category">
                        ${cats.map(k=>`<option value="${k}" ${e.category===k?'selected':''}>${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);
        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 (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; }
        });
    }

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