// assets/js/smartflow-component.js

import { buildGraphFromRaw } from './smartflow-graph-core.js';
//import { fetchVoucherRaw } from './smartflow-api.js';
import SmartFlowAPI from './smartflow-api-client.js';

export class SmartFlowComponent {

    // constructor(containerElement, options = {}) {
    //     if (!containerElement) {
    //         throw new Error('SmartFlowComponent requires a container element');
    //     }

    //     this.container = containerElement;

    //     this.options = {
    //         defaultView: options.defaultView || 'account_level',
    //         dimensions: options.dimensions || [],
    //         greedyFlow: options.greedyFlow !== false,
    //         debug: options.debug || false,
    //         ...options,
    //     };

    //     this.graph = null;
    //     this.currentView = this.options.defaultView;
    // }
    constructor(containerElement, { apiClient, ...options } = {}) {

        if (!containerElement) {
            throw new Error('SmartFlowComponent requires a container element');
        }

        if (!apiClient) {
            throw new Error('SmartFlowComponent requires an apiClient instance');
        }

        this.container = containerElement;

        // API layer
        this.api = new SmartFlowAPI(apiClient);

        this.options = {
            defaultView: options.defaultView || 'account_level',
            dimensions: options.dimensions || [],
            greedyFlow: options.greedyFlow !== false,
            debug: options.debug || false,
            ...options,
        };

        this.graph = null;
        this.currentView = this.options.defaultView;
    }


    // async load(voucherId) {
    //     this.setLoading(true);

    //     try {
    //         const raw = await fetchVoucherRaw(voucherId);

    //         this.graph = buildGraphFromRaw(raw, {
    //             view: this.options.defaultView,
    //             dimensions: this.options.dimensions,
    //             greedyFlow: this.options.greedyFlow,
    //         });

    //         this.currentView = this.graph.views.default || this.options.defaultView;

    //         this.render();

    //     } catch (err) {
    //         this.renderError(err);
    //     } finally {
    //         this.setLoading(false);
    //     }
    // }

    async load(voucherId) {
        this.setLoading(true);

        try {
            const raw = await this.api.fetchVoucherRaw(voucherId);

            this.graph = buildGraphFromRaw(raw, {
                view: this.options.defaultView,
                dimensions: this.options.dimensions,
                greedyFlow: this.options.greedyFlow,
            });

            this.currentView = this.graph.views?.default || this.options.defaultView;

            this.render();

        } catch (err) {
            if (this.options.debug) {
                console.error('SmartFlow load error:', err);
            }

            this.renderError(err);
        } finally {
            this.setLoading(false);
        }
    }


    setLoading(isLoading) {
        if (isLoading) {
            this.container.innerHTML = '<div class="smartflow-loading">در حال بارگذاری...</div>';
        }
    }

    render() {
        if (!this.graph) {
            this.container.innerHTML = '<div class="smartflow-empty">No graph data</div>';
            return;
        }

        this.container.innerHTML = '';

        const toolbar = this.renderToolbar();
        this.container.appendChild(toolbar);

        const graphContainer = document.createElement('div');
        graphContainer.className = 'smartflow-graph-container';

        const viewGraph = this.getGraphForCurrentView();

        // جدول اصلی
        graphContainer.appendChild(this.renderAccountingTable(viewGraph));

        // جدول روابط حساب‌ها (جدید)
        graphContainer.appendChild(this.renderRelationTable(viewGraph));

        // JSON Debug
        if (this.options.debug) {
            const pre = document.createElement('pre');
            pre.className = 'smartflow-graph-json';
            pre.textContent = JSON.stringify(viewGraph, null, 2);
            graphContainer.appendChild(pre);
        }

        this.container.appendChild(graphContainer);
    }

    renderToolbar() {
        const wrapper = document.createElement('div');
        wrapper.className = 'smartflow-toolbar';

        const label = document.createElement('span');
        label.textContent = 'View: ';
        wrapper.appendChild(label);

        const select = document.createElement('select');

        const availableViews = Object.keys(this.graph.views)
            .filter((key) => key !== 'default');

        availableViews.forEach((viewName) => {
            const opt = document.createElement('option');
            opt.value = viewName;
            opt.textContent = viewName;
            if (viewName === this.currentView) {
                opt.selected = true;
            }
            select.appendChild(opt);
        });

        select.addEventListener('change', () => {
            this.setView(select.value);
        });

        wrapper.appendChild(select);

        return wrapper;
    }

    setView(viewName) {
        if (!this.graph || !this.graph.views[viewName]) {
            console.warn(`View "${viewName}" not found`);
            return;
        }

        this.currentView = viewName;
        this.render();
    }

    getGraphForCurrentView() {
        if (!this.graph) return null;

        const viewDef = this.graph.views[this.currentView];
        if (!viewDef) return this.graph;

        const nodeIdSet = new Set(viewDef.nodes);
        const edgeIdSet = new Set(viewDef.edges);

        const nodes = this.graph.nodes.filter(n => nodeIdSet.has(n.id));
        const edges = this.graph.edges.filter(e => edgeIdSet.has(e.id));

        return { nodes, edges, view: this.currentView };
    }

    //
    // -------------- جدول حسابداری (Line-Level) ----------------
    //

    renderAccountingTable(viewGraph) {

        const wrapper = document.createElement('div');
        wrapper.className = 'smartflow-table-wrapper';

        if (!viewGraph || !viewGraph.nodes) {
            wrapper.innerHTML = 'No data';
            return wrapper;
        }

        const lineNodes = viewGraph.nodes.filter(n => n.type === 'LINE');

        if (!lineNodes.length) {
            wrapper.innerHTML = 'No LINE nodes in this view';
            return wrapper;
        }

        lineNodes.sort((a, b) => (a.data?.line_no || 0) - (b.data?.line_no || 0));

        let totalDebit = 0;
        let totalCredit = 0;

        const table = document.createElement('table');
        table.className = 'smartflow-table';

        table.innerHTML = `
            <thead>
                <tr>
                    <th>ردیف</th>
                    <th>کد حساب</th>
                    <th>نام حساب</th>
                    <th>بدهکار</th>
                    <th>بستانکار</th>
                    <th>ابعاد</th>
                </tr>
            </thead>
            <tbody></tbody>
            <tfoot>
                <tr>
                    <th colspan="3">جمع</th>
                    <th class="num"></th>
                    <th class="num"></th>
                    <th></th>
                </tr>
            </tfoot>
        `;

        const tbody = table.querySelector('tbody');

        lineNodes.forEach(node => {

            const d = node.data || {};
            const debit = d.debit || 0;
            const credit = d.credit || 0;

            totalDebit += debit;
            totalCredit += credit;

            const dims = d.dimensions || d.raw?.dimensions || {};
            const dimsText = Object.entries(dims)
                .map(([k, v]) => `${k}: ${v}`)
                .join(' | ');

            const tr = document.createElement('tr');

            tr.innerHTML = `
                <td>${d.line_no || ''}</td>
                <td>${d.account_code || ''}</td>
                <td>${d.account_name || ''}</td>
                <td class="num">${debit ? debit.toLocaleString('fa-IR') : ''}</td>
                <td class="num">${credit ? credit.toLocaleString('fa-IR') : ''}</td>
                <td>${dimsText}</td>
            `;

            tbody.appendChild(tr);
        });

        const tfootNums = table.querySelectorAll('tfoot .num');
        tfootNums[0].textContent = totalDebit.toLocaleString('fa-IR');
        tfootNums[1].textContent = totalCredit.toLocaleString('fa-IR');

        wrapper.appendChild(table);

        return wrapper;
    }

    //
    // -------------- جدول روابط حساب‌ها (Graph → Table) ----------------
    //
    renderRelationTable(viewGraph) {

        const wrapper = document.createElement('div');
        wrapper.className = 'smartflow-table-wrapper';
        wrapper.style.marginTop = "25px";

        const table = document.createElement('table');
        table.className = 'smartflow-table';

        // استایل برای رنگ‌ها
        const style = document.createElement('style');
        style.textContent = `
            .sf-debit {
                color: #0a7f00;
                font-weight: bold;
            }
            .sf-credit {
                color: #b30000;
                font-weight: bold;
            }
        `;
        wrapper.appendChild(style);

        table.innerHTML = `
            <thead>
                <tr>
                    <th>LINE</th>
                    <th>DEBIT ACCOUNT</th>
                    <th>CREDIT ACCOUNT</th>
                    <th>AMOUNT</th>
                    <th>DIMENSIONS</th>
                </tr>
            </thead>
            <tbody></tbody>
        `;

        const tbody = table.querySelector('tbody');

        // فقط یال‌های FLOW را می‌خواهیم (رابطه واقعی بدهکار → بستانکار)
        const flowEdges = viewGraph.edges.filter(e => e.type === "FLOW");

        if (!flowEdges.length) {
            wrapper.innerHTML = "No FLOW edges found (no account relations)";
            return wrapper;
        }

        flowEdges.forEach(flow => {

            const debitAcc = flow.from.replace("account:", "");
            const creditAcc = flow.to.replace("account:", "");
            const amount = flow.data.amount || 0;

            // پیدا کردن نود حساب‌ها برای نام حساب
            const debitAccNode = viewGraph.nodes.find(n => n.id === flow.from);
            const creditAccNode = viewGraph.nodes.find(n => n.id === flow.to);

            const debitAccName = debitAccNode?.data?.account_name || "";
            const creditAccName = creditAccNode?.data?.account_name || "";

            // پیدا کردن Line های مربوط به این حساب‌ها
            const debitLine = viewGraph.nodes.find(
                n => n.type === "LINE" && n.data.account_code == debitAcc
            );
            const creditLine = viewGraph.nodes.find(
                n => n.type === "LINE" && n.data.account_code == creditAcc
            );

            const debitLineNo = debitLine?.data?.line_no || "";
            const creditLineNo = creditLine?.data?.line_no || "";

            // نمایش LINE به صورت «1 → 2»
            const lineDisplay = `${debitLineNo} → ${creditLineNo}`;

            // --- ابعاد مشترک ---
            let dimsText = "-";

            if (debitLine?.data?.raw?.dimensions && creditLine?.data?.raw?.dimensions) {
                const d1 = debitLine.data.raw.dimensions;
                const d2 = creditLine.data.raw.dimensions;

                const common = Object.keys(d1)
                    .filter(k => d1[k] === d2[k])       // مقدار مشترک
                    .map(k => `${k}: ${d1[k]}`)
                    .join(" , ");

                if (common) dimsText = common;
            }

            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>${lineDisplay}</td>
    
                <td class="sf-debit">
                    ${debitAcc}<br>
                    <small>${debitAccName}</small>
                </td>
    
                <td class="sf-credit">
                    ${creditAcc}<br>
                    <small>${creditAccName}</small>
                </td>
    
                <td class="num">${amount.toLocaleString('fa-IR')}</td>
    
                <td>${dimsText}</td>
            `;

            tbody.appendChild(tr);
        });

        wrapper.appendChild(table);
        return wrapper;
    }




    renderError(err) {
        console.error(err);
        this.container.innerHTML =
            `<div class="smartflow-error">Error: ${err.message}</div>`;
    }
}


// ---------------- استایل ----------------

const style = document.createElement('style');
style.textContent = `
.smartflow-table {
    width:100%;
    border-collapse:collapse;
    margin-top:10px;
    font-size:13px;
    background:white;
}
.smartflow-table th,
.smartflow-table td {
    border:1px solid #ddd;
    padding:6px;
}
.smartflow-table thead {
    background:#f3f3f3;
}
.smartflow-table tfoot {
    background:#fafafa;
    font-weight:bold;
}
.smartflow-table .num {
    text-align:right;
}
.smartflow-toolbar {
    margin-bottom:10px;
}
.smartflow-loading {
    padding:10px;
}
.smartflow-error {
    padding:10px;
    color:red;
}
`;
document.head.appendChild(style);
