/**
 * FinancialReportsSection.js
 * گزارش‌های مالی: تراز آزمایشی، دفتر کل، ژورنال جریان
 */

import SectionBase from "../SectionBase.js";
const BaseView = SectionBase;

const REPORT_TABS = [
    { key: "trial_balance",   label: "📊 تراز آزمایشی" },
    { key: "income",          label: "📈 سود و زیان" },
    { key: "balance_sheet",   label: "⚖️ ترازنامه" },
    { key: "ledger",          label: "📒 دفتر کل" },
    { key: "flow_journal",    label: "📝 ژورنال جریان" },
];

export default class FinancialReportsSection extends BaseView {

    static title = "";

    constructor(props = {}) {
        super(props);
        this.api       = props.api;
        this._activeTab = "trial_balance";
        this._accounts  = [];
    }

    async template() {
        const tabBtns = REPORT_TABS.map(t => `
            <button class="reports-tab-btn ${t.key === this._activeTab ? "reports-tab-btn--active" : ""}"
                    data-tab="${t.key}">${t.label}</button>
        `).join("");

        const panels = REPORT_TABS.map(t => `
            <div class="reports-content ${t.key === this._activeTab ? "reports-content--active" : ""}"
                 data-panel="${t.key}" data-ref="panel-${t.key}"></div>
        `).join("");

        return `
            <div class="reports-tabs" data-ref="tabBar">${tabBtns}</div>
            ${panels}
        `;
    }

    async afterRender() {
        // tab switching
        this.ref("tabBar").querySelectorAll(".reports-tab-btn").forEach(btn => {
            this.on(btn, "click", () => this._switchTab(btn.dataset.tab));
        });

        // load accounts for ledger filter
        try {
            const res   = await this.api.get("/accounting/accounts");
            this._accounts = res?.data ?? [];
        } catch { /* non-fatal */ }

        await this._loadActiveTab();
    }

    async _switchTab(key) {
        if (key === this._activeTab) return;

        this.ref("tabBar").querySelectorAll(".reports-tab-btn").forEach(b => {
            b.classList.toggle("reports-tab-btn--active", b.dataset.tab === key);
        });

        this.container.querySelectorAll(".reports-content").forEach(p => {
            p.classList.toggle("reports-content--active", p.dataset.panel === key);
        });

        this._activeTab = key;
        await this._loadActiveTab();
    }

    async _loadActiveTab() {
        const panel = this.ref(`panel-${this._activeTab}`);
        if (!panel) return;

        switch (this._activeTab) {
            case "trial_balance": await this._renderTrialBalance(panel); break;
            case "income":        await this._renderIncomeStatement(panel); break;
            case "balance_sheet": await this._renderBalanceSheet(panel);  break;
            case "ledger":        this._renderLedgerShell(panel);        break;
            case "flow_journal":  await this._renderFlowJournal(panel);  break;
        }
    }

    /* ============================================================
       تراز آزمایشی
    ============================================================ */

    async _renderTrialBalance(panel) {
        panel.innerHTML = `
            <div class="report-filter-bar">
                <label>از تاریخ</label>
                <input type="date" data-ref="tbFrom">
                <label>تا تاریخ</label>
                <input type="date" data-ref="tbTo">
                <button class="acc-btn acc-btn--primary acc-btn--sm" data-ref="tbRun">اجرا</button>
            </div>
            <div data-ref="tbResult"></div>
        `;

        // bind refs locally inside panel
        const fromInput = panel.querySelector("[data-ref='tbFrom']");
        const toInput   = panel.querySelector("[data-ref='tbTo']");
        const runBtn    = panel.querySelector("[data-ref='tbRun']");
        const result    = panel.querySelector("[data-ref='tbResult']");

        runBtn.addEventListener("click", async () => {
            await this._fetchTrialBalance(result, fromInput.value, toInput.value);
        });

        // بارگذاری اولیه بدون فیلتر
        await this._fetchTrialBalance(result, "", "");
    }

    async _fetchTrialBalance(container, from, to) {
        container.innerHTML = `<div class="acc-loading"><div class="acc-spinner"></div>در حال محاسبه...</div>`;

        try {
            const params = {};
            if (from) params.date_from = from;
            if (to)   params.date_to   = to;

            const res  = await this.api.get("/accounting/reports/trial-balance", params);
            const rows = res?.data ?? [];

            if (!rows.length) {
                container.innerHTML = `<div class="acc-empty">داده‌ای یافت نشد.</div>`;
                return;
            }

            let totalDebit = 0, totalCredit = 0, totalNet = 0;
            rows.forEach(r => {
                totalDebit  += Number(r.total_debit  ?? 0);
                totalCredit += Number(r.total_credit ?? 0);
                totalNet    += Number(r.net_balance  ?? 0);
            });

            container.innerHTML = `
                <table class="tb-table">
                    <thead>
                        <tr>
                            <th>کد</th>
                            <th>نام حساب</th>
                            <th>جمع بدهکار</th>
                            <th>جمع بستانکار</th>
                            <th>مانده خالص</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${rows.map(r => `
                            <tr>
                                <td style="font-family:monospace;font-size:12px;color:#94a3b8;">${this.escape(r.code ?? "")}</td>
                                <td>${this.escape(r.name)}</td>
                                <td class="num">${this._fmt(r.total_debit)}</td>
                                <td class="num">${this._fmt(r.total_credit)}</td>
                                <td class="num ${Number(r.net_balance) >= 0 ? "tb-positive" : "tb-negative"}">
                                    ${this._fmt(r.net_balance)}
                                </td>
                            </tr>
                        `).join("")}
                    </tbody>
                    <tfoot>
                        <tr class="tb-table__footer">
                            <td colspan="2">جمع کل</td>
                            <td class="num">${this._fmt(totalDebit)}</td>
                            <td class="num">${this._fmt(totalCredit)}</td>
                            <td class="num ${totalNet >= 0 ? "tb-positive" : "tb-negative"}">${this._fmt(totalNet)}</td>
                        </tr>
                    </tfoot>
                </table>
            `;
        } catch {
            container.innerHTML = `<div class="acc-error">خطا در دریافت تراز آزمایشی</div>`;
        }
    }

    /* ============================================================
       صورت سود و زیان
    ============================================================ */

    async _renderIncomeStatement(panel) {
        panel.innerHTML = `
            <div class="report-filter-bar">
                <label>از تاریخ</label><input type="date" data-ref="isFrom">
                <label>تا تاریخ</label><input type="date" data-ref="isTo">
                <button class="acc-btn acc-btn--primary acc-btn--sm" data-ref="isRun">اجرا</button>
            </div>
            <div data-ref="isResult"></div>`;
        const from = panel.querySelector("[data-ref='isFrom']");
        const to   = panel.querySelector("[data-ref='isTo']");
        const run  = panel.querySelector("[data-ref='isRun']");
        const res  = panel.querySelector("[data-ref='isResult']");
        run.addEventListener("click", () => this._fetchIncome(res, from.value, to.value));
        await this._fetchIncome(res, "", "");
    }

    async _fetchIncome(container, from, to) {
        container.innerHTML = `<div class="acc-loading"><div class="acc-spinner"></div>در حال محاسبه...</div>`;
        try {
            const params = {};
            if (from) params.date_from = from;
            if (to)   params.date_to   = to;
            const r = await this.api.get("/accounting/reports/income-statement", params);
            const d = r?.data;
            if (!d) { container.innerHTML = `<div class="acc-empty">داده‌ای یافت نشد.</div>`; return; }

            const section = (title, rows, total, color) => `
                <tr class="is-section"><td colspan="2">${title}</td></tr>
                ${rows.length
                    ? rows.map(x => `<tr><td>${this.escape(x.code)} ${this.escape(x.name)}</td><td class="num">${this._fmt(x.amount)}</td></tr>`).join("")
                    : `<tr><td colspan="2" style="color:#94a3b8;font-size:12px;">—</td></tr>`}
                <tr class="is-subtotal"><td>جمع ${title}</td><td class="num" style="color:${color}">${this._fmt(total)}</td></tr>`;

            const niColor = Number(d.net_income) >= 0 ? "#059669" : "#dc2626";
            container.innerHTML = `
                <table class="tb-table"><tbody>
                    ${section("درآمد", d.revenue, d.revenue_total, "#059669")}
                    ${d.contra.length ? section("کسوراتِ فروش", d.contra, d.contra_total, "#dc2626") : ""}
                    <tr class="is-net"><td>خالص فروش</td><td class="num">${this._fmt(d.net_sales)}</td></tr>
                    ${section("هزینه‌ها", d.expense, d.expense_total, "#dc2626")}
                    <tr class="is-final"><td>${Number(d.net_income) >= 0 ? "سود" : "زیان"} خالص دوره</td>
                        <td class="num" style="color:${niColor};font-weight:800;">${this._fmt(Math.abs(d.net_income))}</td></tr>
                </tbody></table>`;
        } catch {
            container.innerHTML = `<div class="acc-error">خطا در دریافت صورت سود و زیان</div>`;
        }
    }

    /* ============================================================
       ترازنامه
    ============================================================ */

    async _renderBalanceSheet(panel) {
        panel.innerHTML = `
            <div class="report-filter-bar">
                <label>تا تاریخ</label><input type="date" data-ref="bsTo">
                <button class="acc-btn acc-btn--primary acc-btn--sm" data-ref="bsRun">اجرا</button>
            </div>
            <div data-ref="bsResult"></div>`;
        const to  = panel.querySelector("[data-ref='bsTo']");
        const run = panel.querySelector("[data-ref='bsRun']");
        const res = panel.querySelector("[data-ref='bsResult']");
        run.addEventListener("click", () => this._fetchBalanceSheet(res, to.value));
        await this._fetchBalanceSheet(res, "");
    }

    async _fetchBalanceSheet(container, to) {
        container.innerHTML = `<div class="acc-loading"><div class="acc-spinner"></div>در حال محاسبه...</div>`;
        try {
            const params = {};
            if (to) params.date_to = to;
            const r = await this.api.get("/accounting/reports/balance-sheet", params);
            const d = r?.data;
            if (!d) { container.innerHTML = `<div class="acc-empty">داده‌ای یافت نشد.</div>`; return; }

            const sec = (title, rows, total) => `
                <tr class="is-section"><td colspan="2">${title}</td></tr>
                ${rows.length
                    ? rows.map(x => `<tr><td>${this.escape(x.code)} ${this.escape(x.name)}</td><td class="num">${this._fmt(x.amount)}</td></tr>`).join("")
                    : `<tr><td colspan="2" style="color:#94a3b8;font-size:12px;">—</td></tr>`}
                <tr class="is-subtotal"><td>جمع ${title}</td><td class="num">${this._fmt(total)}</td></tr>`;

            const niColor = Number(d.net_income) >= 0 ? "#059669" : "#dc2626";
            const balBadge = d.balanced
                ? `<span class="status-badge status-badge--confirmed">✓ تراز است</span>`
                : `<span class="status-badge status-badge--cancelled">✗ اختلاف: ${this._fmt(d.difference)}</span>`;

            container.innerHTML = `
                <div style="display:flex;gap:16px;flex-wrap:wrap;">
                    <div style="flex:1;min-width:280px;">
                        <table class="tb-table"><tbody>${sec("دارایی‌ها", d.asset, d.asset_total)}</tbody></table>
                    </div>
                    <div style="flex:1;min-width:280px;">
                        <table class="tb-table"><tbody>
                            ${sec("بدهی‌ها", d.liability, d.liability_total)}
                            ${sec("حقوق صاحبان سهام", d.equity, d.equity_total)}
                            <tr><td>${Number(d.net_income) >= 0 ? "سود" : "زیان"} انباشتهٔ دوره</td>
                                <td class="num" style="color:${niColor}">${this._fmt(Math.abs(d.net_income))}</td></tr>
                            <tr class="is-final"><td>جمع بدهی + حقوق</td><td class="num">${this._fmt(d.liab_equity_total)}</td></tr>
                        </tbody></table>
                    </div>
                </div>
                <div style="text-align:center;margin-top:14px;font-size:14px;">
                    دارایی ${this._fmt(d.asset_total)} = بدهی+حقوق ${this._fmt(d.liab_equity_total)} &nbsp; ${balBadge}
                </div>`;
        } catch {
            container.innerHTML = `<div class="acc-error">خطا در دریافت ترازنامه</div>`;
        }
    }

    /* ============================================================
       دفتر کل
    ============================================================ */

    _renderLedgerShell(panel) {
        const accOptions = this._accounts.map(a =>
            `<option value="${a.id}">${this.escape(a.code + " — " + a.name)}</option>`
        ).join("");

        panel.innerHTML = `
            <div class="report-filter-bar">
                <label>حساب</label>
                <select data-ref="ldgAccount" style="min-width:200px;">
                    <option value="">انتخاب کنید...</option>
                    ${accOptions}
                </select>
                <label>از</label>
                <input type="date" data-ref="ldgFrom">
                <label>تا</label>
                <input type="date" data-ref="ldgTo">
                <button class="acc-btn acc-btn--primary acc-btn--sm" data-ref="ldgRun">نمایش</button>
            </div>
            <div data-ref="ldgResult"></div>
        `;

        const accSel = panel.querySelector("[data-ref='ldgAccount']");
        const from   = panel.querySelector("[data-ref='ldgFrom']");
        const to     = panel.querySelector("[data-ref='ldgTo']");
        const runBtn = panel.querySelector("[data-ref='ldgRun']");
        const result = panel.querySelector("[data-ref='ldgResult']");

        runBtn.addEventListener("click", async () => {
            const accId = accSel.value;
            if (!accId) { alert("لطفاً یک حساب انتخاب کنید."); return; }
            await this._fetchLedger(result, accId, from.value, to.value);
        });
    }

    async _fetchLedger(container, accountId, from, to) {
        container.innerHTML = `<div class="acc-loading"><div class="acc-spinner"></div>در حال بارگذاری...</div>`;

        try {
            const params = { account_id: accountId };
            if (from) params.date_from = from;
            if (to)   params.date_to   = to;

            const res  = await this.api.get("/accounting/reports/ledger", params);
            const rows = res?.data ?? [];

            if (!rows.length) {
                container.innerHTML = `<div class="acc-empty">تراکنشی در این بازه یافت نشد.</div>`;
                return;
            }

            const accountName = this._accounts.find(a => String(a.id) === String(accountId))?.name ?? "";
            const finalBalance = rows[rows.length - 1]?.running_balance ?? 0;

            container.innerHTML = `
                <div class="ledger-header">
                    <span class="ledger-header__title">دفتر کل — ${this.escape(accountName)}</span>
                    <span class="ledger-header__balance">مانده نهایی: ${this._fmt(finalBalance)} ریال</span>
                </div>
                <table class="flows-table" style="border-radius:0 0 10px 10px;overflow:hidden;">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>نوع رویداد</th>
                            <th>مبلغ</th>
                            <th>جهت</th>
                            <th>مانده</th>
                            <th>تاریخ</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${rows.map((r, i) => {
                            const dir   = r.direction === "in"  ? "⬇ ورودی" : "⬆ خروجی";
                            const color = r.direction === "in"  ? "#059669"  : "#dc2626";
                            return `
                                <tr>
                                    <td style="font-size:11px;color:#94a3b8;">${i + 1}</td>
                                    <td>${this.escape(r.event_type ?? "")}</td>
                                    <td class="num">${this._fmt(r.amount)}</td>
                                    <td style="color:${color};font-weight:600;">${dir}</td>
                                    <td class="num">${this._fmt(r.running_balance)}</td>
                                    <td style="font-size:12px;color:#64748b;">${r.created_at ? r.created_at.split("T")[0] : ""}</td>
                                </tr>
                            `;
                        }).join("")}
                    </tbody>
                </table>
            `;
        } catch {
            container.innerHTML = `<div class="acc-error">خطا در دریافت دفتر کل</div>`;
        }
    }

    /* ============================================================
       ژورنال جریان
    ============================================================ */

    async _renderFlowJournal(panel) {
        panel.innerHTML = `
            <div class="report-filter-bar">
                <label>از تاریخ</label>
                <input type="date" data-ref="jFrom">
                <label>تا تاریخ</label>
                <input type="date" data-ref="jTo">
                <label>وضعیت تأیید</label>
                <select data-ref="jConfirmed">
                    <option value="">همه</option>
                    <option value="1">تأییدشده</option>
                    <option value="0">پیش‌نویس</option>
                </select>
                <button class="acc-btn acc-btn--primary acc-btn--sm" data-ref="jRun">اجرا</button>
            </div>
            <div data-ref="jResult"></div>
        `;

        const fromInput  = panel.querySelector("[data-ref='jFrom']");
        const toInput    = panel.querySelector("[data-ref='jTo']");
        const confSel    = panel.querySelector("[data-ref='jConfirmed']");
        const runBtn     = panel.querySelector("[data-ref='jRun']");
        const result     = panel.querySelector("[data-ref='jResult']");

        runBtn.addEventListener("click", () =>
            this._fetchJournal(result, fromInput.value, toInput.value, confSel.value)
        );

        await this._fetchJournal(result, "", "", "");
    }

    async _fetchJournal(container, from, to, confirmed) {
        container.innerHTML = `<div class="acc-loading"><div class="acc-spinner"></div>در حال بارگذاری...</div>`;

        try {
            const params = {};
            if (from)       params.date_from  = from;
            if (to)         params.date_to    = to;
            if (confirmed !== "") params.is_confirmed = confirmed;

            const res   = await this.api.get("/accounting/reports/flow-journal", params);
            const rows  = res?.data ?? [];

            if (!rows.length) {
                container.innerHTML = `<div class="acc-empty">جریانی یافت نشد.</div>`;
                return;
            }

            container.innerHTML = `
                <table class="flows-table">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>رویداد</th>
                            <th>نوع</th>
                            <th>از حساب</th>
                            <th>به حساب</th>
                            <th>مبلغ (ریال)</th>
                            <th>تأیید</th>
                            <th>تاریخ</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${rows.map((f, i) => `
                            <tr>
                                <td style="font-size:11px;color:#94a3b8;">${i + 1}</td>
                                <td style="font-family:monospace;font-size:12px;">#${f.event_id}</td>
                                <td>${this.escape(f.event_type ?? "")}</td>
                                <td>
                                    <span class="flow-direction__from" style="font-size:11px;">
                                        ${this.escape(f.from_account_name ?? "#" + f.from_account_id)}
                                    </span>
                                </td>
                                <td>
                                    <span class="flow-direction__to" style="font-size:11px;">
                                        ${this.escape(f.to_account_name ?? "#" + f.to_account_id)}
                                    </span>
                                </td>
                                <td class="num flow-amount">${this._fmt(f.amount)}</td>
                                <td>
                                    <span class="status-badge ${f.is_confirmed ? "status-badge--confirmed" : "status-badge--draft"}">
                                        ${f.is_confirmed ? "✓" : "⏳"}
                                    </span>
                                </td>
                                <td style="font-size:11px;color:#64748b;">${f.created_at ? f.created_at.split("T")[0] : ""}</td>
                            </tr>
                        `).join("")}
                    </tbody>
                </table>
            `;
        } catch {
            container.innerHTML = `<div class="acc-error">خطا در دریافت ژورنال</div>`;
        }
    }

    /* ---------- Helpers ---------- */

    _fmt(val) {
        return new Intl.NumberFormat("fa-IR").format(Number(val ?? 0));
    }
}
