'use client';

import DataTable, { DataTableColumn } from '@/components/table/DataTable';
import PriceChange from '@/components/table/PriceChange';
import { CommodityRow, COMMODITY_MARKET_LABEL } from '@/types/market';
import { formatNumber } from '@/lib/utils/stock';
import { formatDecimal } from '@/lib/utils/market';

function buildColumns(): DataTableColumn<CommodityRow>[] {
	return [
		{
			key: 'name',
			header: '종목명',
			align: 'left',
			priority: 'high',
			cellClassName: 'data-table__cell--name',
			cell: (row) => (
				<span className='stock-cell'>
					<span className='stock-cell__name'>{row.name}</span>
					<span className='stock-cell__code'>{row.code}</span>
				</span>
			)
		},
		{
			key: 'market',
			header: '시장',
			align: 'center',
			priority: 'low',
			cell: (row) => <span className='market__cls-badge'>{COMMODITY_MARKET_LABEL[row.market] ?? row.market}</span>
		},
		{
			key: 'close',
			header: '현재가',
			align: 'right',
			priority: 'high',
			cell: (row) => formatDecimal(row.close)
		},
		{
			key: 'change',
			header: '등락률',
			align: 'right',
			priority: 'high',
			cell: (row) => <PriceChange rate={row.changeRate} />
		},
		{
			key: 'weighted',
			header: '가중평균가',
			align: 'right',
			priority: 'low',
			cell: (row) => formatDecimal(row.weightedDiscussionPrice)
		},
		{
			key: 'volume',
			header: '거래량',
			align: 'right',
			priority: 'medium',
			cell: (row) => formatNumber(row.volume)
		}
	];
}

export default function CommoditiesTable({ rows }: { rows: CommodityRow[] })
{
	return (
		<DataTable<CommodityRow>
			caption='상품 목록 — 종목명, 시장, 현재가, 등락률, 가중평균가, 거래량'
			columns={buildColumns()}
			rows={rows}
			rowKey={(row) => row.code}
			emptyMessage='표시할 상품이 없습니다.'
		/>
	);
}
