'use client';

import Link from 'next/link';
import DataTable, { DataTableColumn } from '@/components/table/DataTable';
import { MeetingCalendarRow, MEETING_KIND_LABEL } from '@/types/seibro';
import { codeLabel, dateOrDash, meetingTimeLabel } from '@/lib/utils/market';

function buildColumns(): DataTableColumn<MeetingCalendarRow>[] {
	return [
		{
			key: 'name',
			header: '종목명',
			align: 'left',
			priority: 'high',
			cellClassName: 'data-table__cell--name',
			cell: (row) => (
				row.code ? (
					<Link href={`/stock/${row.code}`} className='stock-cell'>
						<span className='stock-cell__name'>{row.name ?? row.code}</span>
						<span className='stock-cell__code'>{row.code}</span>
					</Link>
				) : (
					<span className='stock-cell'>
						<span className='stock-cell__name'>{row.name ?? `발행사 ${row.issucoCustno}`}</span>
					</span>
				)
			)
		},
		{
			key: 'gmetDt',
			header: '총회일',
			align: 'center',
			priority: 'high',
			cell: (row) => {
				const time = meetingTimeLabel(row.gmetTtm);

				return (
					<span>
						{dateOrDash(row.gmetDt)}{time && <span className='market__disclosure-date'> {time}</span>}
					</span>
				);
			}
		},
		{
			key: 'meetingKind',
			header: '종류',
			align: 'center',
			priority: 'high',
			cell: (row) => <span className='market__cls-badge'>{codeLabel(row.meetingKind, MEETING_KIND_LABEL)}</span>
		},
		{
			key: 'evote',
			header: '전자투표',
			align: 'center',
			priority: 'medium',
			cell: (row) => (row.evote === null ? '—' : row.evote ? '가능' : '불가')
		},
		{
			key: 'agendaCount',
			header: '안건수',
			align: 'right',
			priority: 'medium',
			cell: (row) => row.agendaCount.toLocaleString('ko-KR')
		},
		{
			key: 'place',
			header: '장소',
			align: 'left',
			priority: 'low',
			cell: (row) => row.place ?? '—'
		}
	];
}

export default function MeetingCalendarTable({ rows }: { rows: MeetingCalendarRow[] })
{
	return (
		<DataTable<MeetingCalendarRow>
			caption='주총 캘린더 — 종목명, 총회일, 종류, 전자투표, 안건수, 장소'
			columns={buildColumns()}
			rows={rows}
			rowKey={(row, index) => `${row.issucoCustno}-${row.rgtStdDt}-${index}`}
			emptyMessage='표시할 주총 일정이 없습니다.'
		/>
	);
}
