import React, { Fragment, useEffect, useMemo, useRef, useState } from 'react';

import styled from 'styled-components';
import {
	CircularProgressWrapper,
	FormWrapper,
	TableStyle,
	TableWrapper,
} from '../../styles/Components';
import { amountDeltaType, CurrencyType } from '../../assets/data';
import { useTranslation } from 'react-i18next';
import { numberFormatter } from '../../utils';
import { TableSkeleton } from '../Skeleton/TableSkeleton';
import { CurrencyLogSearchBar, useCurrencyLogSearch } from '../searchBar';
import { TopButton, ViewTableInfo } from '../common';
import Pagination from '../common/Pagination/Pagination';
import {
	INITIAL_PAGE_LIMIT,
	STORAGE_BUSINESS_LOG_SEARCH,
	STORAGE_GAME_LOG_CURRENCY_SEARCH,
} from '../../assets/data/adminConstants';
import ExcelExportButton from '../common/button/ExcelExportButton';
import CircularProgress from '../common/CircularProgress';

const CurrencyLogContent = ({ active }) => {
	const { t } = useTranslation();
	const token = sessionStorage.getItem('token');
	const tableRef = useRef(null);
	const [downloadState, setDownloadState] = useState({
		loading: false,
		progress: 0
	});

	const {
		searchParams,
		loading: dataLoading,
		data: dataList,
		handleSearch,
		handleReset,
		handlePageChange,
		handleOrderByChange,
		handlePageSizeChange,
		updateSearchParams
	} = useCurrencyLogSearch(token, 500);

	useEffect(() => {
		if(active) {
			// 세션 스토리지에서 복사된 메일 데이터 가져오기
			const paramsData = sessionStorage.getItem(STORAGE_GAME_LOG_CURRENCY_SEARCH);

			if (paramsData) {
				const searchData = JSON.parse(paramsData);

				handleSearch({
					start_dt: new Date(searchData.start_dt),
					end_dt: new Date(searchData.end_dt),
					search_data: searchData.guid
				});

				// 사용 후 세션 스토리지 데이터 삭제
				sessionStorage.removeItem(STORAGE_GAME_LOG_CURRENCY_SEARCH);
			}
		}
	}, [active]);

	const tableHeaders = useMemo(() => {
		return [
			// { id: 'logDay', label: '일자', width: '120px' },
			{ id: 'logTime', label: '일시', width: '120px' },
			{ id: 'accountId', label: 'account ID', width: '80px' },
			{ id: 'userGuid', label: 'GUID', width: '200px' },
			{ id: 'userNickname', label: '아바타명', width: '150px' },
			{ id: 'tranId', label: '트랜잭션 ID', width: '200px' },
			{ id: 'action', label: '액션', width: '150px' },
			{ id: 'currencyType', label: '재화종류', width: '120px' },
			{ id: 'amountDeltaType', label: '증감유형', width: '120px' },
			{ id: 'deltaAmount', label: '수량', width: '120px' },
			// { id: 'deltaAmount', label: '수량원본', width: '120px' },
			{ id: 'currencyAmount', label: '잔량', width: '120px' },
		];
	}, []);

	if(!active) return null;

	return (
		<>
			<FormWrapper>
				<CurrencyLogSearchBar
					searchParams={searchParams}
					onSearch={(newParams, executeSearch = true) => {
						if (executeSearch) {
							handleSearch(newParams);
						} else {
							updateSearchParams(newParams);
						}
					}}
					onReset={handleReset}
				/>
			</FormWrapper>
			<ViewTableInfo orderType="asc" pageType="B" total={dataList?.total} total_all={dataList?.total_all}>
				<ExcelExportButton
					functionName="GameCurrencyDetailLogExport"
					params={searchParams}
					fileName={t('FILE_GAME_LOG_CURRENCY')}
					onLoadingChange={setDownloadState}
					dataSize={dataList?.total_all}
				/>
				{downloadState.loading && (
					<CircularProgressWrapper>
						<CircularProgress
							progress={downloadState.progress}
							size={36}
							progressColor="#4A90E2"
						/>
					</CircularProgressWrapper>
				)}
			</ViewTableInfo>
			{dataLoading ? <TableSkeleton width='100%' count={15} /> :
				<>
					<TableWrapper>
						<TableStyle ref={tableRef}>
							<thead>
							<tr>
								{tableHeaders.map(header => (
									<th key={header.id} width={header.width}>{header.label}</th>
								))}
							</tr>
							</thead>
							<tbody>
							{dataList?.currency_detail_list?.map((item, index) => (
								<Fragment key={index}>
									<tr>
										<td>{item.logTime}</td>
										<td>{item.accountId}</td>
										<td>{item.userGuid}</td>
										<td>{item.userNickname}</td>
										<td>{item.tranId}</td>
										<td>{item.action}</td>
										<td>{CurrencyType.find(data => data.value === item.currencyType)?.name}</td>
										<td>{amountDeltaType.find(data => data.value === item.amountDeltaType)?.name}</td>
										<td>{numberFormatter.formatCurrency(item.deltaAmount)}</td>
										{/*<td>{item.deltaAmount}</td>*/}
										<td>{numberFormatter.formatCurrency(item.currencyAmount)}</td>
									</tr>
								</Fragment>
							))}
							</tbody>
						</TableStyle>
					</TableWrapper>
					{dataList?.currency_detail_list &&
						<Pagination
							postsPerPage={searchParams.page_size}
							totalPosts={dataList?.total_all}
							setCurrentPage={handlePageChange}
							currentPage={searchParams.page_no}
							pageLimit={INITIAL_PAGE_LIMIT}
						/>
					}
					<TopButton />
				</>
			}
		</>
	);
};
export default CurrencyLogContent;