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, LandInfoData } from '../../../apis';
import { landAuctionStatus, landSearchType, landSize, opLandCategoryType } from '../../../assets/data';
import { opLandInfoStatusType } from '../../../assets/data/options';

export const useLandInfoSearch = (token, initialPageSize) => {
	const [searchParams, setSearchParams] = useState({
		landType: 'ID',
		landData: '',
		landSize: 'ALL',
		category: 'ALL',
		status: 'ALL',
		startDate: '',
		endDate: '',
		orderBy: 'DESC',
		pageSize: initialPageSize,
		currentPage: 1
	});

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

	useEffect(() => {
		// fetchData(searchParams); // 컴포넌트 마운트 시 초기 데이터 로드
		const initialLoad = async () => {
			await fetchData(searchParams);
		};

		initialLoad();
	}, [token]);

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

		try {
			setLoading(true);
			const result = await LandInfoData(
				token,
				params.landType,
				params.landData,
				params.landSize,
				params.category,
				params.status,
				params.startDate && new Date(params.startDate).toISOString(),
				params.endDate && new Date(params.endDate).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: '',
			landSize: 'ALL',
			category: 'ALL',
			status: 'ALL',
			startDate: '',
			endDate: '',
			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 LandInfoSearchBar = ({ 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>
			<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)} >
				{opLandInfoStatusType.map((data, index) => (
					<option key={index} value={data.value}>
						{data.name}
					</option>
				))}
			</SelectInput>
		</>,
	];

	const optionList = [
		<>
			<InputLabel>카테고리</InputLabel>
			<SelectInput value={searchParams.category} onChange={e => onSearch({ category: e.target.value }, false)}>
				{opLandCategoryType.map((data, index) => (
					<option key={index} value={data.value}>
						{data.name}
					</option>
				))}
			</SelectInput>
		</>,
		<>
			<InputLabel>일자</InputLabel>
			<SearchPeriod
				startDate={searchParams.startDate}
				handleStartDate={date => onSearch({ startDate: date }, false)}
				endDate={searchParams.endDate}
				handleEndDate={date => onSearch({ endDate: date }, false)}
			/>
		</>,
		<></>,<></>,
		<>
			<BtnWrapper $gap="8px">
				<Button theme="reset" handleClick={onReset} type="button" />
				<Button theme="search" text="검색" handleClick={handleSubmit} type="submit" />
			</BtnWrapper>
		</>,
	];
	return <SearchBarLayout firstColumnData={searchList} secondColumnData={optionList} direction={'column'} />;
};

export default LandInfoSearchBar;