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

import {
	CircularProgressWrapper,
	FormWrapper,
	TableStyle,
	TableWrapper,
} from '../../styles/Components';
import { useTranslation } from 'react-i18next';
import { TableSkeleton } from '../Skeleton/TableSkeleton';
import { useUserLoginLogSearch, UserLoginLogSearchBar } from '../searchBar';
import { TopButton, ViewTableInfo } from '../common';
import Pagination from '../common/Pagination/Pagination';
import {
	INITIAL_PAGE_LIMIT, STORAGE_GAME_LOG_USER_LOGIN_SEARCH,
} from '../../assets/data/adminConstants';
import ExcelExportButton from '../common/button/ExcelExportButton';
import CircularProgress from '../common/CircularProgress';
import { AnimatedPageWrapper } from '../common/Layout';
import { numberFormatter } from '../../utils';

const UserLoginLogContent = ({ 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
	} = useUserLoginLogSearch(token, 500);

	useEffect(() => {
		if(active) {
			// 세션 스토리지에서 복사된 메일 데이터 가져오기
			const paramsData = sessionStorage.getItem(STORAGE_GAME_LOG_USER_LOGIN_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_USER_LOGIN_SEARCH);
			}
		}
	}, [active]);

	const tableHeaders = useMemo(() => {
		return [
			{ id: 'logDay', label: '일자', width: '100px' },
			{ id: 'accountId', label: 'account ID', width: '80px' },
			{ id: 'userGuid', label: 'GUID', width: '180px' },
			{ id: 'userNickname', label: '아바타명', width: '150px' },
			{ id: 'tranId', label: '트랜잭션 ID', width: '200px' },
			{ id: 'loginTime', label: '로그인시간', width: '150px' },
			{ id: 'logoutTime', label: '로그아웃시간', width: '120px' },
			{ id: 'serverType', label: '서버종류', width: '80px' },
			{ id: 'languageType', label: '언어', width: '80px' },
			{ id: 'playtime', label: '플레이시간(분)', width: '80px' },
		];
	}, []);

	if(!active) return null;

	return (
		<AnimatedPageWrapper>
			<FormWrapper>
				<UserLoginLogSearchBar
					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="GameUserLoginLogExport"
					params={searchParams}
					fileName={t('FILE_GAME_LOG_USER_LOGIN')}
					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?.user_login_list?.map((item, index) => (
								<Fragment key={index}>
									<tr>
										<td>{item.logDay}</td>
										<td>{item.accountId}</td>
										<td>{item.userGuid}</td>
										<td>{item.userNickname}</td>
										<td>{item.tranId}</td>
										<td>{item.loginTime}</td>
										<td>{item.logoutTime}</td>
										<td>{item.serverType}</td>
										<td>{item.languageType}</td>
										<td>{numberFormatter.formatSecondToMinuts(item.playtime)}</td>
									</tr>
								</Fragment>
							))}
							</tbody>
						</TableStyle>
					</TableWrapper>
					{dataList?.user_login_list &&
						<Pagination
							postsPerPage={searchParams.page_size}
							totalPosts={dataList?.total_all}
							setCurrentPage={handlePageChange}
							currentPage={searchParams.page_no}
							pageLimit={INITIAL_PAGE_LIMIT}
						/>
					}
					<TopButton />
				</>
			}
		</AnimatedPageWrapper>
	);
};
export default UserLoginLogContent;