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

export const useCurrencyIndexSearch = (token, initialPageSize) => {
	const {showToast} = useAlert();

	const [searchParams, setSearchParams] = useState({
		start_dt: (() => {
			const date = new Date();
			date.setDate(date.getDate() - 1);
			return date;
		})(),
		end_dt: (() => {
			const date = new Date();
			date.setDate(date.getDate());
			return date;
		})(),
		order_by: 'ASC',
		page_size: initialPageSize,
		page_no: 1
	});

	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 getCurrencyList(
				token,
				params.start_dt.toISOString(),
				params.end_dt.toISOString(),
				params.order_by,
				params.page_size,
				params.page_no
			);
			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});
			}else if(result.result === "ERROR"){
				showToast(result.result, {type: alertTypes.error});
			}
			setData(result.data);
			return result.data;
		} catch (error) {
			showToast('error', {type: alertTypes.error});
			throw error;
		} finally {
			setLoading(false);
		}
	}, [token]);

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

	const handleSearch = useCallback(async (newParams = {}, executeSearch = true) => {
		const updatedParams = {
			...searchParams,
			...newParams,
			page_no: newParams.page_no || 1 // Reset to first page on new search
		};
		updateSearchParams(updatedParams);

		if (executeSearch) {
			return await fetchData(updatedParams);
		}
		return null;
	}, [searchParams, fetchData]);

	const handleReset = useCallback(async () => {
		const now = new Date();
		now.setDate(now.getDate() - 1);
		const resetParams = {
			start_dt: now,
			end_dt: new Date(),
			order_by: 'ASC',
			page_size: initialPageSize,
			page_no: 1
		};
		setSearchParams(resetParams);
		return await fetchData(resetParams);
	}, [initialPageSize, fetchData]);

	const handlePageChange = useCallback(async (newPage) => {
		return await handleSearch({ page_no: newPage }, true);
	}, [handleSearch]);

	const handlePageSizeChange = useCallback(async (newSize) => {
		return await handleSearch({ page_size: newSize, page_no: 1 }, true);
	}, [handleSearch]);

	const handleOrderByChange = useCallback(async (newOrder) => {
		return await handleSearch({ order_by: newOrder }, true);
	}, [handleSearch]);

	return {
		searchParams,
		loading,
		data,
		handleSearch,
		handleReset,
		handlePageChange,
		handlePageSizeChange,
		handleOrderByChange,
		updateSearchParams
	};
};

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

		onSearch(searchParams, true);
	};

	const searchList = [
		<>
			<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 CurrencyIndexSearchBar;