'use client';

import DataTable, { DataTableColumn } from '@/components/table/DataTable';
import { EsgIndexRow } from '@/types/market';
import { formatNumber, changeDirection, changeSymbol } from '@/lib/utils/stock';
import { formatDecimal, formatBpRate } from '@/lib/utils/market';

function buildColumns(): DataTableColumn<EsgIndexRow>[] {
	return [
		{
			key: 'name',
			header: '지수명',
			align: 'left',
			priority: 'high',
			cellClassName: 'data-table__cell--name',
			cell: (row) => <span className='stock-cell__name'>{row.name}</span>
		},
		{
			key: 'close',
			header: '지수',
			align: 'right',
			priority: 'high',
			cell: (row) => formatDecimal(row.close)
		},
		{
			key: 'change',
			header: '등락률',
			align: 'right',
			priority: 'high',
			cell: (row) => {
				const direction = changeDirection(row.flucRateBp);

				return (
					<span className={`market__index-change market__index-change--${direction}`}>
						<span aria-hidden='true'>{changeSymbol(direction)}</span> {formatBpRate(row.flucRateBp)}
					</span>
				);
			}
		},
		{
			key: 'constituents',
			header: '구성종목수',
			align: 'right',
			priority: 'medium',
			cell: (row) => formatNumber(row.constituentCount)
		},
		{
			key: 'volume',
			header: '거래량',
			align: 'right',
			priority: 'low',
			cell: (row) => formatNumber(row.volume)
		}
	];
}

export default function EsgIndicesTable({ rows }: { rows: EsgIndexRow[] })
{
	return (
		<DataTable<EsgIndexRow>
			caption='ESG 지수 목록 — 지수명, 지수, 등락률, 구성종목수, 거래량'
			columns={buildColumns()}
			rows={rows}
			rowKey={(row, index) => `${row.name}-${index}`}
			emptyMessage='표시할 ESG 지수가 없습니다.'
		/>
	);
}
