import { useMemo } from 'react';
import { PivotBoard } from '@/Components/Pivot/PivotBoard';
import { LegacyGrid } from '@/Components/MenuCompanies/CompanyTabPanels';
import { formatGrouped } from '@/lib/currencyFormat';
import { DemoDataBadge } from '@/Components/NetSuite/DemoDataBadge';

/**
 * "Details Inv-Analysis" pane (NetSuite `ns-sj-analysis` and AST `ast-sj-analysis`).
 *
 * The port shipped this pane as a FLAT line list, which lost what the legacy screen was
 * for: legacy ran PivotTable.js (`rows: NamaBarang`, `cols: [Tahun, Bulan]`, Heatmap) and
 * every dimension was draggable. Reported 2026-08-24 — *"tampilan inv-analisis kayaknya
 * enakan yang dulu, di kolom tabel per bulan, dan bisa geser-geser yang dimau… gue mau tau
 * total penjualan per tahun agak bingung"*.
 *
 * So this restores three things, in the order they were asked for:
 *   1. a YEAR STRIP — omzet per Tahun, always visible, because that was the question the
 *      flat table could not answer at all (no totals row exists anywhere on it);
 *   2. the PIVOT, opening on the legacy layout (product rows × year·month columns) with the
 *      same drag-and-drop, plus the row/column/grand totals PivotBoard already renders;
 *   3. the raw line list, unchanged, below it — nothing that was visible got taken away.
 *
 * Shape-agnostic on purpose: the server sends `{cols, rows}` where rows are POSITIONAL
 * arrays, and the two integrations do not agree on the measure columns (NetSuite ends in
 * InvAmount/RAAmount/TotalQt/TotalAmount, AST in SumQt/Price/Subtotal). Rather than keep
 * two vocabularies in sync by hand, dimensions are named here and everything else is
 * treated as a measure — a new measure column starts working with no change to this file.
 */

// The dimension columns both integrations share. `No` is a row counter, not a field.
const DIMENSION_COLS = ['Tahun', 'Bulan', 'Company', 'PrincipalName', 'NamaBarang', 'NamaAlias'];

// Default measure, first match wins: NetSuite's net-of-returns figure is TotalAmount, AST's
// is Subtotal. InvAmount is the gross fallback if a source ever ships neither.
const PREFERRED_MEASURE = ['TotalAmount', 'Subtotal', 'InvAmount', 'Amount'];

const LABELS = { PrincipalName: 'Principal', NamaBarang: 'Nama Barang', NamaAlias: 'Nama Alias' };

export function CompanyInvAnalysisPane({ cols = [], rows = [], notice = '', isDemoData = false, demoSource = 'NetSuite' }) {
    const model = useMemo(() => {
        const dims = cols.filter((c) => DIMENSION_COLS.includes(c));
        const measures = cols.filter((c) => c !== 'No' && !DIMENSION_COLS.includes(c));
        const measure = PREFERRED_MEASURE.find((m) => measures.includes(m)) ?? measures[0] ?? '';

        // Positional arrays → keyed facts. The column NAME is the field id, so the pivot's
        // field chips read the same words the details table's headers do.
        const facts = rows.map((row) => {
            const fact = {};
            cols.forEach((c, i) => { fact[c] = row[i]; });
            return fact;
        });

        // Omzet per year. Kept as its own reduce rather than read off the pivot: the pivot's
        // layout is the user's to rearrange, and this strip has to keep answering the same
        // question after they drag Tahun out of it.
        const perYear = new Map();
        if (measure && dims.includes('Tahun')) {
            for (const f of facts) {
                const year = String(f.Tahun ?? '').trim();
                if (year === '') continue;
                perYear.set(year, (perYear.get(year) ?? 0) + (Number(f[measure]) || 0));
            }
        }

        return {
            facts,
            measure,
            fields: dims.map((d) => ({ id: d, label: LABELS[d] ?? d })),
            measures: measures.map((m) => ({ id: m, label: m })),
            years: [...perYear.entries()].sort((a, b) => a[0].localeCompare(b[0])),
        };
    }, [cols, rows]);

    // No rows: LegacyGrid already renders the server's notice ("Customer Tidak Memiliki
    // Data SJ" / "Customer Have No Synchronization"), so let it keep owning that state.
    if (!rows || rows.length === 0) {
        return <LegacyGrid cols={cols} rows={rows} notice={notice} isDemoData={isDemoData} demoSource={demoSource} />;
    }

    const currentYear = String(new Date().getFullYear());

    return (
        <div className="flex flex-col gap-5">
            <DemoDataBadge show={isDemoData} source={demoSource} />
            {model.years.length > 0 && (
                <div>
                    <p className="m-0 mb-2 text-[11px] font-bold uppercase tracking-wide text-muted-foreground">
                        Omzet per tahun · {model.measure}
                    </p>
                    <div className="flex flex-wrap gap-2">
                        {model.years.map(([year, total]) => (
                            <div key={year}
                                className="min-w-[128px] flex-1 rounded-lg border border-border bg-secondary/40 px-3.5 py-2.5">
                                <span className="block text-[11px] font-bold text-muted-foreground">
                                    {/* The running year is partial by definition — say so, or the
                                        number reads as a full year that collapsed. */}
                                    {year}{year === currentYear ? ' (YTD)' : ''}
                                </span>
                                <span className="block text-[15px] font-extrabold tabular-nums text-card-foreground">
                                    {formatGrouped(total, { decimals: 0 })}
                                </span>
                            </div>
                        ))}
                    </div>
                </div>
            )}

            <PivotBoard
                rows={model.facts}
                fields={model.fields}
                measures={model.measures}
                initial={{
                    // Legacy layout verbatim (listnssjanalysispm.php): product down the side,
                    // year → month across the top, summed, heatmap.
                    rows: model.fields.some((f) => f.id === 'NamaBarang') ? ['NamaBarang'] : [],
                    cols: model.fields.filter((f) => f.id === 'Tahun' || f.id === 'Bulan').map((f) => f.id),
                    measure: model.measure,
                    agg: 'sum',
                    renderer: 'heatmap',
                }}
            />

            <div>
                <p className="m-0 mb-2 text-[11px] font-bold uppercase tracking-wide text-muted-foreground">Details</p>
                <LegacyGrid cols={cols} rows={rows} notice={notice} />
            </div>
        </div>
    );
}
