import { TextInput, BtnWrapper, InputLabel, SelectInput, InputGroup } from '../../styles/Components';
import Button from '../common/button/Button';
import { SearchBarLayout, SearchPeriod } from '../common/SearchBar';
import { useCallback, useEffect, useState } from 'react';
import { LandAuctionView } from '../../apis';
import { landAuctionStatus, landSearchType, landSize, userType } from '../../assets/data';

export const useLandAuctionSearch = (token, initialPageSize) => {
	const [searchParams, setSearchParams] = useState({
		landType: 'ID',
		landData: '',
		userType: 'GUID',
		userData: '',
		landSize: 'ALL',
		status: 'ALL',
		auctionStartDate: '',
		auctionEndDate: '',
		orderBy: 'DESC',
		pageSize: initialPageSize,
		currentPage: 1
	});

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

	useEffect(() => {
		fetchData(searchParams); // 컴포넌트 마운트 시 초기 데이터 로드
	}, [token]);

	const fetchData = useCallback(async (params) => {
		try {
			setLoading(true);
			const result = await LandAuctionView(
				token,
				params.landType,
				params.landData,
				params.userType,
				params.userData,
				params.landSize,
				params.status,
				params.auctionStartDate && new Date(params.auctionStartDate).toISOString(),
				params.auctionEndDate && new Date(params.auctionEndDate).toISOString(),
				params.orderBy,
				params.pageSize,
				params.currentPage
			);
			setData(result);
			return result;
		} 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,
			currentPage: newParams.currentPage || 1 // Reset to first page on new search
		};
		updateSearchParams(updatedParams);
		return await fetchData(updatedParams);
	}, [searchParams, fetchData]);

	const handleReset = useCallback(async () => {
		const resetParams = {
			landType: 'ID',
			landData: '',
			userType: 'GUID',
			userData: '',
			landSize: 'ALL',
			status: 'ALL',
			auctionStartDate: '',
			auctionEndDate: '',
			orderBy: 'DESC',
			pageSize: initialPageSize,
			currentPage: 1
		};
		setSearchParams(resetParams);
		return await fetchData(resetParams);
	}, [initialPageSize, fetchData]);

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

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

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

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

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

		onSearch(searchParams);
	};

	const searchList = [
		<>
			<InputGroup>
				<SelectInput value={searchParams.landType} onChange={e => onSearch({landType: e.target.value })}>
					{landSearchType.map((data, index) => (
						<option key={index} value={data.value}>
							{data.name}
						</option>
					))}
				</SelectInput>
				<TextInput
					type="text"
					placeholder={searchParams.landType === 'ID' ? '랜드 ID 입력' : '랜드명 입력'}
					value={searchParams.landData}
					width="300px"
					onChange={e => onSearch({ landData: e.target.value })}
				/>
			</InputGroup>
		</>,
		<>
			<InputLabel>낙찰자</InputLabel>
			<InputGroup>
				<SelectInput value={searchParams.userType} onChange={e => onSearch({userType: e.target.value })}>
					{userType.map((data, index) => (
						<option key={index} value={data.value}>
							{data.name}
						</option>
					))}
				</SelectInput>
				<TextInput
					type="text"
					placeholder={searchParams.userType === 'GUID' ? 'GUID 입력' : '닉네임 입력'}
					value={searchParams.userData}
					width="300px"
					onChange={e => onSearch({ userData: e.target.value })}
				/>
			</InputGroup>
		</>
	];

	const optionList = [
		<>
			<InputLabel>랜드크기</InputLabel>
			<SelectInput value={searchParams.landSize} onChange={e => onSearch({ landSize: e.target.value }, false)} >
				{landSize.map((data, index) => (
					<option key={index} value={data.value}>
						{data.name}
					</option>
				))}
			</SelectInput>
		</>,
		<>
			<InputLabel>경매상태</InputLabel>
			<SelectInput value={searchParams.status} onChange={e => onSearch({ status: e.target.value }, false)}>
				{landAuctionStatus.map((data, index) => (
					<option key={index} value={data.value}>
						{data.name}
					</option>
				))}
			</SelectInput>
		</>,
		<>
			<InputLabel>경매 일자</InputLabel>
			<SearchPeriod
				startDate={searchParams.auctionStartDate}
				handleStartDate={date => onSearch({ auctionStartDate: date }, false)}
				endDate={searchParams.auctionEndDate}
				handleEndDate={date => onSearch({ auctionEndDate: date }, false)}
			/>
		</>,
	];
	return <SearchBarLayout firstColumnData={searchList} secondColumnData={optionList} direction={'column'} onReset={onReset} handleSubmit={handleSubmit} />;
};

export default LandAuctionSearchBar;