import React, { Fragment, useRef } from 'react';

import { TableStyle, TableInfo, ListOption, IndexTableWrap } from '../../styles/Components';
import { AnimatedPageWrapper } from '../common/Layout';
import { useRetentionSearch, RetentionSearchBar } from '../searchBar';
import { TableSkeleton } from '../Skeleton/TableSkeleton';
import { numberFormatter } from '../../utils';
import { ExcelDownButton } from '../common';
import { useTranslation } from 'react-i18next';

const RetentionContent = () => {
	const { t } = useTranslation();
	const tableRef = useRef(null);
	const token = sessionStorage.getItem('token');

	const {
		searchParams,
		loading: dataLoading,
		data: dataList,
		handleSearch,
		handleReset,
		updateSearchParams
	} = useRetentionSearch(token);


	return (
		<AnimatedPageWrapper>
			<RetentionSearchBar
				searchParams={searchParams}
				onSearch={(newParams, executeSearch = true) => {
					if (executeSearch) {
						handleSearch(newParams);
					} else {
						updateSearchParams(newParams);
					}
				}}
				onReset={handleReset}
			/>
			<TableInfo>
				<ListOption>
					<ExcelDownButton tableRef={tableRef} fileName={t('FILE_INDEX_USER_RETENTION')} />
				</ListOption>
			</TableInfo>
			{dataLoading ? <TableSkeleton width='100%' count={15} /> :
				<IndexTableWrap>
					<TableStyle ref={tableRef}>
						<caption></caption>
						<thead>
							<tr>
								<th>일자</th>
								<th>NRU</th>
								<th>D+1</th>
								<th>D+7</th>
								<th>D+30</th>
							</tr>
						</thead>
						<tbody>
							{dataList?.map((data, index) => (
								<Fragment key={index}>
									<tr>
										<td>{data.logDay}</td>
										<td>{data.totalCreated}</td>
										<td>{numberFormatter.formatPercent(data.d1_rate)}</td>
										<td>{numberFormatter.formatPercent(data.d7_rate)}</td>
										<td>{numberFormatter.formatPercent(data.d30_rate)}</td>
									</tr>
								</Fragment>
								))}
						</tbody>
					</TableStyle>
				</IndexTableWrap>
			}
		</AnimatedPageWrapper>
	);
};

export default RetentionContent;
