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

import {
	TableStyle,
	FormWrapper,
	TableWrapper, CircularProgressWrapper, TotalRow,
} from '../../styles/Components';

import { useCurrencyIndexSearch } from '../searchBar';
import { Button, TopButton, ViewTableInfo } from '../common';
import { TableSkeleton } from '../Skeleton/TableSkeleton';
import { numberFormatter } from '../../utils';
import {STORAGE_GAME_LOG_CURRENCY_SEARCH, } from '../../assets/data/adminConstants';
import ExcelExportButton from '../common/button/ExcelExportButton';
import CircularProgress from '../common/CircularProgress';
import { useTranslation } from 'react-i18next';
import CurrencyIndexSearchBar from '../searchBar/CurrencyIndexSearchBar';
import { useNavigate } from 'react-router-dom';
import { AnimatedPageWrapper } from '../common/Layout';

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

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

	const tableHeaders = useMemo(() => {
		return [
			// 기본 컬럼 (rowSpan=2)
			{ id: 'logDay', label: '일자', width: '100px', rowSpan: 2 },
			{ id: 'accountId', label: 'account ID', width: '80px', rowSpan: 2 },
			{ id: 'userGuid', label: 'GUID', width: '200px', rowSpan: 2 },
			{ id: 'userNickname', label: '아바타명', width: '150px', rowSpan: 2 },

			// 획득량 그룹 헤더 (첫 번째 행에만 표시)
			{ id: 'acquired', label: '획득', width: '400px', colSpan: 5, groupHeader: true },

			// 획득량 컬럼 (두 번째 행에만 표시)
			{ id: 'sapphireAcquired', label: '사파이어', width: '80px', groupRow: true },
			{ id: 'goldAcquired', label: '골드', width: '80px', groupRow: true },
			{ id: 'caliumAcquired', label: '칼리움', width: '80px', groupRow: true },
			{ id: 'beamAcquired', label: 'BEAM', width: '80px', groupRow: true },
			{ id: 'rubyAcquired', label: '루비', width: '80px', groupRow: true },

			// 소모량 그룹 헤더 (첫 번째 행에만 표시)
			{ id: 'consumed', label: '소모', width: '400px', colSpan: 5, groupHeader: true },

			// 소모량 컬럼 (두 번째 행에만 표시)
			{ id: 'sapphireConsumed', label: '사파이어', width: '80px', groupRow: true },
			{ id: 'goldConsumed', label: '골드', width: '80px', groupRow: true },
			{ id: 'caliumConsumed', label: '칼리움', width: '80px', groupRow: true },
			{ id: 'beamConsumed', label: 'BEAM', width: '80px', groupRow: true },
			{ id: 'rubyConsumed', label: '루비', width: '80px', groupRow: true },

			// 계 컬럼 (rowSpan=2)
			{ id: 'sapphireNet', label: '사파이어 계', width: '80px', rowSpan: 2 },
			{ id: 'goldNet', label: '골드 계', width: '80px', rowSpan: 2 },
			{ id: 'caliumNet', label: '칼리움 계', width: '80px', rowSpan: 2 },
			{ id: 'beamNet', label: 'BEAM 계', width: '80px', rowSpan: 2 },
			{ id: 'rubyNet', label: '루비 계', width: '80px', rowSpan: 2 },

			// 기타 컬럼 (rowSpan=2)
			{ id: 'totalCurrencies', label: '활동 수', width: '80px', rowSpan: 2 },
			{ id: 'detail', label: '상세', width: '100px', rowSpan: 2 }
		];

	}, []);


	const totals = useMemo(() => {
		if (!dataList?.currency_list?.length) return null;

		return dataList.currency_list.reduce((acc, item) => {
			return {
				sapphireAcquired: (acc.sapphireAcquired || 0) + (item.sapphireAcquired || 0),
				sapphireConsumed: (acc.sapphireConsumed || 0) + (item.sapphireConsumed || 0),
				goldAcquired: (acc.goldAcquired || 0) + (item.goldAcquired || 0),
				goldConsumed: (acc.goldConsumed || 0) + (item.goldConsumed || 0),
				caliumAcquired: (acc.caliumAcquired || 0) + (item.caliumAcquired || 0),
				caliumConsumed: (acc.caliumConsumed || 0) + (item.caliumConsumed || 0),
				beamAcquired: (acc.beamAcquired || 0) + (item.beamAcquired || 0),
				beamConsumed: (acc.beamConsumed || 0) + (item.beamConsumed || 0),
				rubyAcquired: (acc.rubyAcquired || 0) + (item.rubyAcquired || 0),
				rubyConsumed: (acc.rubyConsumed || 0) + (item.rubyConsumed || 0),
				sapphireNet: (acc.sapphireNet || 0) + (item.sapphireNet || 0),
				goldNet: (acc.goldNet || 0) + (item.goldNet || 0),
				caliumNet: (acc.caliumNet || 0) + (item.caliumNet || 0),
				beamNet: (acc.beamNet || 0) + (item.beamNet || 0),
				rubyNet: (acc.rubyNet || 0) + (item.rubyNet || 0),
				totalCurrencies: (acc.totalCurrencies || 0) + (item.totalCurrencies || 0),
			};
		}, {});
	}, [dataList?.currency_list]);

	const handleModalSubmit = async (type, param = null) => {
		switch (type) {
			case "detail":
				const params = {
					tab: "CURRENCY",
					start_dt: (() => {
						const date = new Date(param.logDay);
						return date;
					})(),
					end_dt: (() => {
						const date = new Date(param.logDay);
						date.setDate(date.getDate() + 1);
						return date;
					})(),
					guid: param.userGuid
				};

				// 복사한 데이터를 세션 스토리지에 저장
				sessionStorage.setItem(STORAGE_GAME_LOG_CURRENCY_SEARCH, JSON.stringify(params));
				navigate('/datamanage/gamelogview');
				break;
		}
	}

	return (
		<AnimatedPageWrapper>
			<FormWrapper>
				<CurrencyIndexSearchBar
					searchParams={searchParams}
					onSearch={(newParams, executeSearch = true) => {
						if (executeSearch) {
							handleSearch(newParams);
						} else {
							updateSearchParams(newParams);
						}
					}}
					onReset={handleReset}
				/>
			</FormWrapper>
			<ViewTableInfo >
				<ExcelExportButton
					functionName="GameCurrencyLogExport"
					params={searchParams}
					fileName={t('FILE_CURRENCY_INDEX')}
					onLoadingChange={setDownloadState}
					dataSize={dataList?.length}
				/>
				{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>
								{/* 첫 번째 행 - 기본 컬럼 + 그룹 헤더 + rowSpan=2 컬럼 */}
								{tableHeaders.map(header => {
									if (header.groupRow) return null; // 두 번째 행의 컬럼은 첫 번째 행에서 건너뜀

									return (
										<th
											key={header.id}
											width={header.width}
											rowSpan={header.rowSpan}
											colSpan={header.colSpan}
										>
											{header.label}
										</th>
									);
								})}
							</tr>
							<tr>
								{/* 두 번째 행 - 그룹 내 하위 컬럼만 */}
								{tableHeaders.map(header => {
									if (!header.groupRow) return null; // 첫 번째 행이나 rowSpan=2 컬럼은 두 번째 행에서 건너뜀

									return (
										<th key={header.id} width={header.width}>
											{header.label}
										</th>
									);
								})}
							</tr>
							</thead>


							<tbody>
							{totals && (
								<TotalRow>
									<td colSpan="4">합계</td>
									{/* 획득 그룹 합계 */}
									<td>{numberFormatter.formatCurrency(totals.sapphireAcquired)}</td>
									<td>{numberFormatter.formatCurrency(totals.goldAcquired)}</td>
									<td>{numberFormatter.formatCurrency(totals.caliumAcquired)}</td>
									<td>{numberFormatter.formatCurrency(totals.beamAcquired)}</td>
									<td>{numberFormatter.formatCurrency(totals.rubyAcquired)}</td>

									{/* 소모 그룹 합계 */}
									<td>{numberFormatter.formatCurrency(totals.sapphireConsumed)}</td>
									<td>{numberFormatter.formatCurrency(totals.goldConsumed)}</td>
									<td>{numberFormatter.formatCurrency(totals.caliumConsumed)}</td>
									<td>{numberFormatter.formatCurrency(totals.beamConsumed)}</td>
									<td>{numberFormatter.formatCurrency(totals.rubyConsumed)}</td>

									{/* 계 합계 */}
									<td>{numberFormatter.formatCurrency(totals.sapphireNet)}</td>
									<td>{numberFormatter.formatCurrency(totals.goldNet)}</td>
									<td>{numberFormatter.formatCurrency(totals.caliumNet)}</td>
									<td>{numberFormatter.formatCurrency(totals.beamNet)}</td>
									<td>{numberFormatter.formatCurrency(totals.rubyNet)}</td>

									<td>{totals.totalCurrencies}</td>
									<td>-</td>
								</TotalRow>
							)}
							{dataList?.currency_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>{numberFormatter.formatCurrency(item.sapphireAcquired)}</td>
										<td>{numberFormatter.formatCurrency(item.goldAcquired)}</td>
										<td>{numberFormatter.formatCurrency(item.caliumAcquired)}</td>
										<td>{numberFormatter.formatCurrency(item.beamAcquired)}</td>
										<td>{numberFormatter.formatCurrency(item.rubyAcquired)}</td>

										{/* 소모 그룹 */}
										<td>{numberFormatter.formatCurrency(item.sapphireConsumed)}</td>
										<td>{numberFormatter.formatCurrency(item.goldConsumed)}</td>
										<td>{numberFormatter.formatCurrency(item.caliumConsumed)}</td>
										<td>{numberFormatter.formatCurrency(item.beamConsumed)}</td>
										<td>{numberFormatter.formatCurrency(item.rubyConsumed)}</td>

										{/* 계 */}
										<td>{numberFormatter.formatCurrency(item.sapphireNet)}</td>
										<td>{numberFormatter.formatCurrency(item.goldNet)}</td>
										<td>{numberFormatter.formatCurrency(item.caliumNet)}</td>
										<td>{numberFormatter.formatCurrency(item.beamNet)}</td>
										<td>{numberFormatter.formatCurrency(item.rubyNet)}</td>

										<td>{item.totalCurrencies}</td>
										<td>
											<Button theme="line" text="상세보기"
													handleClick={e => handleModalSubmit('detail', item)} />
										</td>
									</tr>
								</Fragment>
							))}
							</tbody>
						</TableStyle>
					</TableWrapper>
					<TopButton />
				</>
			}
		</AnimatedPageWrapper>
	);
};

export default CreditContent;
