'use client';

import Link from 'next/link';
import DataTable, { DataTableColumn } from '@/components/table/DataTable';
import { LockupCalendarRow, LOCKUP_OCCR_LABEL, LOCKUP_REASON_LABEL } from '@/types/seibro';
import { codeLabel, formatShares, dateOrDash } from '@/lib/utils/market';

function buildColumns(): DataTableColumn<LockupCalendarRow>[] {
	return [
		{
			key: 'name',
			header: '종목명',
			align: 'left',
			priority: 'high',
			cellClassName: 'data-table__cell--name',
			cell: (row) => (
				row.shortCode ? (
					<Link href={`/stock/${row.shortCode}`} className='stock-cell'>
						<span className='stock-cell__name'>{row.name}</span>
						<span className='stock-cell__code'>{row.shortCode}</span>
					</Link>
				) : (
					<span className='stock-cell'>
						<span className='stock-cell__name'>{row.name}</span>
					</span>
				)
			)
		},
		{
			key: 'occrSeq',
			header: '구분',
			align: 'center',
			priority: 'high',
			cell: (row) => <span className='market__cls-badge'>{codeLabel(row.occrSeq, LOCKUP_OCCR_LABEL)}</span>
		},
		{
			key: 'safedpDt',
			header: '예수일',
			align: 'center',
			priority: 'medium',
			cell: (row) => row.safedpDt
		},
		{
			key: 'returnDt',
			header: '해제일',
			align: 'center',
			priority: 'high',
			cell: (row) => dateOrDash(row.returnDt)
		},
		{
			key: 'qty',
			header: '수량',
			align: 'right',
			priority: 'high',
			cell: (row) => formatShares(row.returnQty ?? row.safedpQty)
		},
		{
			key: 'reason',
			header: '사유',
			align: 'center',
			priority: 'low',
			cell: (row) => codeLabel(row.reasonCode, LOCKUP_REASON_LABEL)
		}
	];
}

export default function LockupCalendarTable({ rows }: { rows: LockupCalendarRow[] })
{
	return (
		<DataTable<LockupCalendarRow>
			caption='락업(보호예수) 캘린더 — 종목명, 구분, 예수일, 해제일, 수량, 사유'
			columns={buildColumns()}
			rows={rows}
			rowKey={(row, index) => `${row.shortCode}-${row.safedpDt}-${row.occrSeq}-${index}`}
			emptyMessage='표시할 락업 일정이 없습니다.'
		/>
	);
}
