'use client';

import DataTable, { DataTableColumn, ColumnPriority } from '@/components/table/DataTable';
import { MacroIndicator, MACRO_CODE_LABEL } from '@/types/macro';
import { macroPeriodLabel, formatMacroValue } from '@/lib/utils/market';

interface MacroTableRow {
	period: string;
	// 지표 코드 → 해당 시점 값 (미수록 시점은 null)
	values: Record<string, number|null>;
}

// 지표 열 우선순위 — 앞쪽 지표만 mobile 유지 (지표 6열 전부는 협소)
function columnPriority(index: number): ColumnPriority {
	if (index < 2) {
		return 'high';
	}

	return index < 4 ? 'medium' : 'low';
}

function buildColumns(indicators: MacroIndicator[]): DataTableColumn<MacroTableRow>[] {
	const columns: DataTableColumn<MacroTableRow>[] = [
		{
			key: 'period',
			header: '시점',
			align: 'left',
			priority: 'high',
			cell: (row) => macroPeriodLabel(row.period)
		}
	];

	indicators.forEach((indicator, index) => {
		const label = MACRO_CODE_LABEL[indicator.code] ?? indicator.name;

		columns.push({
			key: indicator.code,
			header: indicator.unit ? `${label} (${indicator.unit})` : label,
			align: 'right',
			priority: columnPriority(index),
			cell: (row) => formatMacroValue(row.values[indicator.code])
		});
	});

	return columns;
}

// 최근 N기간 매트릭스 — 행 = 시점(내림차순 = 최신 먼저), 열 = 지표
export default function MacroTable({ indicators, maxRows = 12 }: { indicators: MacroIndicator[]; maxRows?: number })
{
	const valueMaps = new Map<string, Map<string, number>>();
	const periods = new Set<string>();

	for (const indicator of indicators) {
		const map = new Map<string, number>();

		for (const point of indicator.points) {
			map.set(point.period, point.value);
			periods.add(point.period);
		}

		valueMaps.set(indicator.code, map);
	}

	const rows: MacroTableRow[] = [...periods]
		.sort((a, b) => b.localeCompare(a))
		.slice(0, maxRows)
		.map(period => ({
			period,
			values: Object.fromEntries(indicators.map(indicator => [indicator.code, valueMaps.get(indicator.code)?.get(period) ?? null]))
		}));

	return (
		<DataTable<MacroTableRow>
			caption='거시경제지표 최근 추이 — 시점별 고용률, 실업률, 취업자수, 소비자물가지수, 수출액, 수입액'
			columns={buildColumns(indicators)}
			rows={rows}
			rowKey={(row) => row.period}
			emptyMessage='표시할 거시지표 데이터가 없습니다.'
		/>
	);
}