import { InputLabel, TextInput } from '../../styles/Components';
import { SearchBarLayout, SearchPeriod } from '../common/SearchBar';
import { useCallback, useEffect, useState } from 'react';
import { InitHistoryList } from '../../apis/Data';
import { useAlert } from '../../context/AlertProvider';
import { alertTypes } from '../../assets/data/types';

export const useDataInitSearch = (token) => {
	const {showToast} = useAlert();

	const [searchParams, setSearchParams] = useState({
		tran_id: '',
		start_dt: (() => {
			return new Date();
		})(),
		end_dt: (() => {
			return new Date();
		})(),
	});

	const [loading, setLoading] = useState(false);
	const [data, setData] = useState(null);

	useEffect(() => {
		const initialLoad = async () => {
			await fetchData(searchParams);
		};

		initialLoad();
	}, [token]);

	const fetchData = useCallback(async (params) => {
		if (!token) return;

		try {
			setLoading(true);
			const result = await InitHistoryList(
				token,
				params
			);
			if(result.result === "ERROR_LOG_MEMORY_LIMIT"){
				showToast('LOG_MEMORY_LIMIT_WARNING',{type: alertTypes.error});
			}else if(result.result === "ERROR_MONGODB_QUERY"){
				showToast('LOG_MONGGDB_QUERY_WARNING',{type: alertTypes.error});
			}
			setData(result.data);
			return result.data;
		} catch (error) {
			console.error('Error fetching auction data:', error);
			throw error;
		} finally {
			setLoading(false);
		}
	}, [token]);

	const updateSearchParams = useCallback((newParams) => {
		setSearchParams(prev => ({
			...prev,
			...newParams
		}));
	}, []);

	const handleSearch = useCallback(async (newParams = {}) => {
		const updatedParams = {
			...searchParams,
			...newParams,
		};
		updateSearchParams(updatedParams);
		return await fetchData(updatedParams);
	}, [searchParams, fetchData]);

	const handleReset = useCallback(async () => {
		const now = new Date();
		const resetParams = {
			tran_id: '',
			start_dt: now,
			end_dt: now,
		};
		setSearchParams(resetParams);
		return await fetchData(resetParams);
	}, [fetchData]);

	return {
		searchParams,
		loading,
		data,
		handleSearch,
		handleReset,
		updateSearchParams
	};
};

const DataInitSearchBar = ({ searchParams, onSearch, onReset }) => {
	const handleSubmit = event => {
		event.preventDefault();

		onSearch(searchParams);
	};

	const searchList = [
		<>
			<InputLabel>트랜잭션 ID</InputLabel>
			<TextInput
				type="text"
				placeholder='트랜잭션 ID 입력'
				value={searchParams.tran_id}
				width="300px"
				onChange={e => onSearch({ tran_id: e.target.value })}
			/>
		</>,
		<>
			<InputLabel>일자</InputLabel>
			<SearchPeriod
				startDate={searchParams.start_dt}
				handleStartDate={date => onSearch({ start_dt: date }, false)}
				endDate={searchParams.end_dt}
				handleEndDate={date => onSearch({ end_dt: date }, false)}
			/>
		</>,
	];

	return <SearchBarLayout firstColumnData={searchList} direction={'column'} onReset={onReset} handleSubmit={handleSubmit} />;
};

export default DataInitSearchBar;