import '../style.scss';
import '@/app/styles/data-table.scss';
import { Metadata } from 'next';
import MarketNav from '../_components/MarketNav';
import MarketFilterTabs from '../_components/MarketFilterTabs';
import BondsTable from '../_components/BondsTable';
import Pager from '../_components/Pager';
import { fetchMarketBonds } from '@/lib/api/market';
import { BondMarketName } from '@/types/market';
import { formatNumber } from '@/lib/utils/stock';
import { tradeDateLabel } from '@/lib/utils/market';

export const metadata: Metadata = {
	title: '채권 — 개미투자',
	description: '국내 채권 시세 — 국채전문·일반채권·소액채권 가격·수익률(YTM)·거래량 (전일 종가 기준)'
};

const MARKET_TABS: { value: BondMarketName; label: string }[] = [
	{ value: 'KtsGovt', label: '국채전문' },
	{ value: 'General', label: '일반채권' },
	{ value: 'Small', label: '소액채권' }
];

const PER_PAGE = 20;

type Props = {
	searchParams: Promise<{
		market?: string;
		page?: string;
	}>;
};

export default async function MarketBondsPage({ searchParams }: Props)
{
	const query = await searchParams;
	const market: BondMarketName = MARKET_TABS.some(c => c.value === query.market) ? (query.market as BondMarketName) : 'KtsGovt';
	const page = Math.max(Number(query.page) || 1, 1);

	const res = await fetchMarketBonds({ market, page });
	const data = res.success ? res.data : null;

	return (
		<div className='market'>
			<div className='market__head'>
				<h1 className='market__title'>채권</h1>
				<span className='market__basis'>{tradeDateLabel(data?.tradeDate)} · 국채전문/일반/소액</span>
			</div>

			<MarketNav />

			<div className='market__filters'>
				<MarketFilterTabs
					label='시장'
					paramKey='market'
					tabs={MARKET_TABS}
					active={market}
					basePath='/market/bonds'
				/>
			</div>

			{!res.success ? (
				<div className='market__error' role='alert'>
					<strong>채권 목록을 불러오지 못했습니다.</strong>
					잠시 후 다시 시도해 주세요.
				</div>
			) : !data || data.list.length === 0 ? (
				<div className='market__empty'>표시할 채권이 없습니다.</div>
			) : (
				<>
					<p className='market__total'>전체 {formatNumber(data.total)}종목</p>
					<div className='market__table-wrap'>
						<BondsTable rows={data.list} />
					</div>
					<Pager
						total={data.total}
						page={page}
						perPage={PER_PAGE}
						basePath='/market/bonds'
						query={{ market }}
					/>
				</>
			)}
		</div>
	);
}
