import { TextInput, InputLabel, SelectInput, InputGroup } from '../../styles/Components';
import { SearchBarLayout, SearchPeriod } from '../common/SearchBar';
import { useCallback, useEffect, useState } from 'react';
import {
	amountDeltaType,
	countDeltaType,
	CurrencyType,
	itemTypeLarge,
	logAction,
	userSearchType2,
} from '../../assets/data/options';
import { getCurrencyDetailList, getItemDetailList } from '../../apis/Log';
import { useAlert } from '../../context/AlertProvider';
import { alertTypes } from '../../assets/data/types';

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

	const [searchParams, setSearchParams] = useState({
		search_type: 'GUID',
		search_data: '',
		tran_id: '',
		log_action: 'None',
		item_large_type: 'None',
		item_small_type: '',
		count_delta_type: 'None',
		start_dt: (() => {
			const date = new Date();
			date.setDate(date.getDate() - 1);
			return date;
		})(),
		end_dt: (() => {
			const date = new Date();
			date.setDate(date.getDate() - 1);
			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 getItemDetailList(
				token,
				params.search_type,
				params.search_data,
				params.tran_id,
				params.log_action,
				params.item_large_type,
				params.item_small_type,
				params.count_delta_type,
				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 = {
			search_type: 'GUID',
			search_data: '',
			tran_id: '',
			log_action: 'None',
			item_large_type: 'None',
			item_small_type: '',
			count_delta_type: 'None',
			start_dt: now,
			end_dt: now,
			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 ItemLogSearchBar = ({ searchParams, onSearch, onReset }) => {
	const handleSubmit = event => {
		event.preventDefault();

		onSearch(searchParams, true);
	};

	const searchList = [
		<>
			<InputGroup>
				<SelectInput value={searchParams.search_type} onChange={e => onSearch({search_type: e.target.value }, false)}>
					{userSearchType2.map((data, index) => (
						<option key={index} value={data.value}>
							{data.name}
						</option>
					))}
				</SelectInput>
				<TextInput
					type="text"
					placeholder={searchParams.search_type === 'GUID' ? 'GUID ID 입력' : searchParams.search_type === 'NICKNAME' ? '아바타명 입력' :'Account ID 입력'}
					value={searchParams.search_data}
					width="260px"
					onChange={e => onSearch({ search_data: e.target.value }, false)}
				/>
			</InputGroup>
		</>,
		<>
			<InputLabel>트랜잭션 ID</InputLabel>
			<TextInput
				type="text"
				placeholder='트랜잭션 ID 입력'
				value={searchParams.tran_id}
				width="300px"
				onChange={e => onSearch({ tran_id: e.target.value }, false)}
			/>
		</>,
		<>
			<InputLabel>LargeType</InputLabel>
			<SelectInput value={searchParams.item_large_type} onChange={e => onSearch({ item_large_type: e.target.value }, false)} >
				<option value="None">전체</option>
				{itemTypeLarge.map((data, index) => (
					<option key={index} value={data.value}>
						{data.name}
					</option>
				))}
			</SelectInput>
		</>,
	];

	const optionList = [
		<>
			<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)}
			/>
		</>,
		<>
			<InputLabel>액션</InputLabel>
			<SelectInput value={searchParams.log_action} onChange={e => onSearch({ log_action: e.target.value }, false)} >
				{logAction.map((data, index) => (
					<option key={index} value={data.value}>
						{data.name}
					</option>
				))}
			</SelectInput>
		</>,
		<>
			<InputLabel>SmallType</InputLabel>
			<TextInput
				type="text"
				placeholder='Small Type 입력'
				value={searchParams.item_small_type}
				width="150px"
				onChange={e => onSearch({ item_small_type: e.target.value }, false)}
			/>
		</>,
		<>
			<InputLabel>증감유형</InputLabel>
			<SelectInput value={searchParams.count_delta_type} onChange={e => onSearch({ count_delta_type: e.target.value }, false)} >
				<option value="None">전체</option>
				{countDeltaType.map((data, index) => (
					<option key={index} value={data.value}>
						{data.name}
					</option>
				))}
			</SelectInput>
		</>,
	];

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

export default ItemLogSearchBar;