'use client';

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

function buildColumns(): DataTableColumn<EtpRow>[] {
	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: 'type',
			header: '종류',
			align: 'center',
			priority: 'medium',
			cell: (row) => <span className='market__cls-badge'>{ETP_TYPE_LABEL[row.type] ?? row.type}</span>
		},
		{
			key: 'close',
			header: '현재가',
			align: 'right',
			priority: 'high',
			cell: (row) => formatNumber(row.close)
		},
		{
			key: 'change',
			header: '등락률',
			align: 'right',
			priority: 'high',
			cell: (row) => <PriceChange rate={row.changeRate} />
		},
		{
			key: 'nav',
			header: 'NAV/IV',
			align: 'right',
			priority: 'low',
			cell: (row) => formatDecimal(row.nav)
		},
		{
			key: 'volume',
			header: '거래량',
			align: 'right',
			priority: 'medium',
			cell: (row) => formatNumber(row.volume)
		},
		{
			key: 'base',
			header: '기초지수/기초자산',
			align: 'left',
			priority: 'low',
			cell: (row) => row.baseIndexName || row.underlying || '—'
		}
	];
}

export default function EtpTable({ rows }: { rows: EtpRow[] })
{
	return (
		<DataTable<EtpRow>
			caption='ETP 목록 — 종목명, 종류, 현재가, 등락률, NAV, 거래량, 기초지수'
			columns={buildColumns()}
			rows={rows}
			rowKey={(row) => row.code}
			emptyMessage='표시할 종목이 없습니다.'
		/>
	);
}
