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

export const metadata: Metadata = {
	title: '상품 (석유·금·배출권) — 개미투자',
	description: '국내 파생상품시장 상품 시세 — 석유·금·배출권 현재가·등락률·거래량 (전일 종가 기준)'
};

const MARKET_TABS: { value: CommodityMarketName; label: string }[] = [
	{ value: 'Oil', label: '석유' },
	{ value: 'Gold', label: '금' },
	{ value: 'Emission', label: '배출권' }
];

const PER_PAGE = 20;

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

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

	const res = await fetchMarketCommodities({ 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/commodities'
				/>
			</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'>
						<CommoditiesTable rows={data.list} />
					</div>
					<Pager
						total={data.total}
						page={page}
						perPage={PER_PAGE}
						basePath='/market/commodities'
						query={{ market }}
					/>
				</>
			)}
		</div>
	);
}
