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

export const metadata: Metadata = {
	title: 'ETP (ETF·ETN·ELW) — 개미투자',
	description: '국내 상장 ETP 시세 — ETF·ETN·ELW 현재가·등락률·NAV·거래량 (전일 종가 기준)'
};

const TYPE_TABS: { value: EtpTypeName; label: string }[] = [
	{ value: 'ETF', label: 'ETF' },
	{ value: 'ETN', label: 'ETN' },
	{ value: 'ELW', label: 'ELW' }
];

const PER_PAGE = 20;

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

export default async function MarketEtpPage({ searchParams }: Props)
{
	const query = await searchParams;
	const type: EtpTypeName = TYPE_TABS.some(c => c.value === query.type) ? (query.type as EtpTypeName) : 'ETF';
	const page = Math.max(Number(query.page) || 1, 1);

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

	return (
		<div className='market'>
			<div className='market__head'>
				<h1 className='market__title'>ETP</h1>
				<span className='market__basis'>{tradeDateLabel(data?.tradeDate)} · ETF/ETN/ELW</span>
			</div>

			<MarketNav />

			<div className='market__filters'>
				<MarketFilterTabs
					label='종류'
					paramKey='type'
					tabs={TYPE_TABS}
					active={type}
					basePath='/market/etp'
				/>
			</div>

			{!res.success ? (
				<div className='market__error' role='alert'>
					<strong>ETP 목록을 불러오지 못했습니다.</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'>
						<EtpTable rows={data.list} />
					</div>
					<Pager
						total={data.total}
						page={page}
						perPage={PER_PAGE}
						basePath='/market/etp'
						query={{ type }}
					/>
				</>
			)}
		</div>
	);
}
