import { TextInput, InputLabel, SelectInput, InputGroup } from '../../../styles/Components';
import { SearchBarLayout, SearchPeriod } from '../../common/SearchBar';
import { useCallback, useEffect, useState } from 'react';
import { logAction, logDomain, userSearchType2 } from '../../../assets/data/options';
import { BusinessLogList } from '../../../apis/Log';
import {SearchFilter} from '../';
import { useAlert } from '../../../context/AlertProvider';
import { alertTypes } from '../../../assets/data/types';

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

	const [searchParams, setSearchParams] = useState({
		search_type: 'GUID',
		search_data: '',
		log_action: 'None',
		log_domain: 'BASE',
		tran_id: '',
		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;
		})(),
		filters: [],
		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 start = Date.now();
			const result = await BusinessLogList(
				token,
				params
			);
			const end = Date.now();
			showToast(`처리 시간: ${end - start}ms`, {type: alertTypes.info});
			console.log(`처리 시간: ${end - start}ms`);
			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: '',
			log_action: 'None',
			log_domain: 'BASE',
			tran_id: '',
			start_dt: now,
			end_dt: now,
			filters: [],
			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 BusinessLogSearchBar = ({ 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>로그액션</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>로그도메인</InputLabel>
			<SelectInput value={searchParams.log_domain} onChange={e => onSearch({ log_domain: e.target.value }, false)} >
				{logDomain.map((data, index) => (
					<option key={index} value={data.value}>
						{data.name}
					</option>
				))}
			</SelectInput>
		</>,
	];

	const optionList = [
		<>
			<InputLabel>트랜잭션 ID</InputLabel>
			<TextInput
				type="text"
				placeholder='트랜잭션 ID 입력'
				value={searchParams.tran_id}
				width="300px"
				onChange={e => onSearch({ tran_id: e.target.value }, false)}
			/>
		</>,
		<>
			<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)}
			/>
		</>,
	];

	const filterComponent = (
		<SearchFilter value={searchParams.filters} onChange={e => onSearch({filters: e.target.value }, false)} />
	);

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

export default BusinessLogSearchBar;