import { ExcelDownButton } from '../../../styles/ModuleComponents';
import { useCallback, useEffect, useRef, useState } from 'react';
import { BusinessLogExport, getExcelProgress } from '../../../apis/Log';
import { useAlert } from '../../../context/AlertProvider';
import { alertTypes } from '../../../assets/data/types';

const ExcelDownloadButton = ({ params, fileName = 'download.xlsx', sheetName = 'Sheet1', onLoadingChange, disabled, dataSize }) => {
	const token = sessionStorage.getItem('token');
	const {showToast} = useAlert();
	const [isDownloading, setIsDownloading] = useState(false);
	const taskIdRef = useRef(null);
	const intervalRef = useRef(null);

	// 진행률 폴링 함수
	const pollProgress = useCallback(async (taskId) => {
		try {
			const response = await getExcelProgress(token, taskId);
			// console.log(response.data);
			if (response.data.exists) {
				const { percentage, message } = response.data;

				if (onLoadingChange) {
					onLoadingChange({
						loading: true,
						progress: percentage
					});
				}

				if (onLoadingChange) {
					onLoadingChange({ loading: true, progress: percentage });
				}

				// 100% 완료 시 폴링 중지
				if (percentage >= 100) {
					clearInterval(intervalRef.current);
					intervalRef.current = null;
				}
			} else {
				// 진행률 정보가 없으면 폴링 중지
				clearInterval(intervalRef.current);
				intervalRef.current = null;
			}
		} catch (error) {
			console.error('Progress polling error:', error);
			// 에러 발생 시 폴링 중지
			clearInterval(intervalRef.current);
			intervalRef.current = null;
		}
	}, [onLoadingChange]);

	// 컴포넌트 언마운트 시 정리
	useEffect(() => {
		return () => {
			if (intervalRef.current) {
				clearInterval(intervalRef.current);
			}
		};
	}, []);

	const handleDownload = useCallback(async () => {
		if (isDownloading) return; // 이미 다운로드 중이면 중복 실행 방지
		if (dataSize > 200000){
			showToast('EXCEL_EXPORT_LENGTH_LIMIT_WARNING', {type: alertTypes.warning});
			return;
		}

		// const start = Date.now();
		const taskId = `excel_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
		taskIdRef.current = taskId;


		setIsDownloading(true);
		if (onLoadingChange) onLoadingChange({loading: true, progress: 0});

		// 진행률 폴링 시작 (1초마다)
		intervalRef.current = setInterval(() => {
			pollProgress(taskId);
		}, 1000);

		try {
			await BusinessLogExport(token, {...params, taskId});

			setTimeout(async () => {
				try {
					await pollProgress(taskId);
				} catch (error) {
					console.error('Final progress check error:', error);
				}
			}, 300);
		} catch (error) {
			console.error('BusinessLogExport API error:', error);
			showToast(error, {type: alertTypes.error});

			if (intervalRef.current) {
				clearInterval(intervalRef.current);
				intervalRef.current = null;
			}
			setIsDownloading(false);
			if (onLoadingChange) {
				onLoadingChange({
					loading: false,
					progress: 0
				});
			}
		} finally {
			if (!intervalRef.current) return;

			// 2초 후 상태 리셋
			setTimeout(() => {
				setIsDownloading(false);

				if (onLoadingChange) {
					onLoadingChange({ loading: false, progress: 100 });
					showToast('DOWNLOAD_COMPLETE', { type: alertTypes.success });
				}

				// 폴링 완전 중지
				if (intervalRef.current) {
					clearInterval(intervalRef.current);
					intervalRef.current = null;
				}

				// const end = Date.now();
				// showToast(`처리 시간: ${end - start}ms`, { type: alertTypes.info });
				// console.log(`처리 시간: ${end - start}ms`);
			}, 2000);
		}
	}, [params, isDownloading, onLoadingChange, dataSize, pollProgress, showToast]);

	return (
		<ExcelDownButton onClick={handleDownload} disabled={isDownloading || dataSize === 0}>
			{isDownloading ? '다운로드 중...' : '엑셀 다운로드'}
		</ExcelDownButton>
	);
};

export default ExcelDownloadButton;