'use client';

import Link from 'next/link';
import DataTable, { DataTableColumn } from '@/components/table/DataTable';
import { BondRow, BOND_MARKET_LABEL } from '@/types/market';
import { formatNumber } from '@/lib/utils/stock';
import { formatDecimal, formatRatePercent } from '@/lib/utils/market';

// KRX 채권 Code 는 12자리 ISIN → 채권 상세 링크 대상
function isIsin(code: string): boolean {
	return /^[A-Za-z0-9]{12}$/.test(code);
}

function buildColumns(): DataTableColumn<BondRow>[] {
	return [
		{
			key: 'name',
			header: '종목명',
			align: 'left',
			priority: 'high',
			cellClassName: 'data-table__cell--name',
			cell: (row) => (
				isIsin(row.code) ? (
					<Link href={`/market/bonds/${row.code}`} className='stock-cell'>
						<span className='stock-cell__name'>{row.name}</span>
						<span className='stock-cell__code'>{row.code}</span>
					</Link>
				) : (
					<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'>{BOND_MARKET_LABEL[row.market] ?? row.market}</span>
		},
		{
			key: 'close',
			header: '가격',
			align: 'right',
			priority: 'high',
			cell: (row) => formatDecimal(row.close)
		},
		{
			key: 'ytm',
			header: '수익률(YTM)',
			align: 'right',
			priority: 'high',
			cell: (row) => formatRatePercent(row.yieldToMaturity, 3)
		},
		{
			key: 'volume',
			header: '거래량',
			align: 'right',
			priority: 'medium',
			cell: (row) => formatNumber(row.volume)
		},
		{
			key: 'maturity',
			header: '만기',
			align: 'center',
			priority: 'low',
			cell: (row) => row.maturityYears || '—'
		}
	];
}

export default function BondsTable({ rows }: { rows: BondRow[] })
{
	return (
		<DataTable<BondRow>
			caption='채권 목록 — 종목명, 시장, 가격, 수익률, 거래량, 만기'
			columns={buildColumns()}
			rows={rows}
			rowKey={(row) => row.code}
			emptyMessage='표시할 채권이 없습니다.'
		/>
	);
}
