import { addHistoryItem, clearHistory, loadHistory, removeHistoryItem } from "../utils/storage.js";
import { useCallback, useEffect, useState } from "react";
//#region src/components/pisellLookup/hooks/useSearchHistory.ts
/**
* 搜索历史管理 Hook
* 支持自定义存储逻辑
*/
const useSearchHistory = (options) => {
	const { historyKey, maxHistoryCount, onLoadHistory, onSaveHistory } = options;
	const [history, setHistory] = useState([]);
	/**
	* 加载历史记录
	*/
	const reloadHistory = useCallback(() => {
		try {
			if (onLoadHistory) {
				const loadedHistory = onLoadHistory();
				setHistory(Array.isArray(loadedHistory) ? loadedHistory : []);
			} else {
				const loadedHistory = loadHistory(historyKey);
				setHistory(Array.isArray(loadedHistory) ? loadedHistory : []);
			}
		} catch (error) {
			console.error("Failed to reload history:", error);
			setHistory([]);
		}
	}, [historyKey, onLoadHistory]);
	/**
	* 初始化：加载历史记录
	*/
	useEffect(() => {
		reloadHistory();
	}, [reloadHistory]);
	return {
		history,
		addHistory: useCallback((keyword) => {
			if (!keyword || !keyword.trim()) return;
			const trimmedKeyword = keyword.trim();
			if (onSaveHistory) {
				const newHistory = [trimmedKeyword, ...(Array.isArray(history) ? history : []).filter((h) => h !== trimmedKeyword)].slice(0, maxHistoryCount);
				setHistory(newHistory);
				onSaveHistory(newHistory);
			} else setHistory(addHistoryItem(historyKey, trimmedKeyword, maxHistoryCount));
		}, [
			history,
			historyKey,
			maxHistoryCount,
			onSaveHistory
		]),
		removeHistory: useCallback((keyword) => {
			if (onSaveHistory) {
				const newHistory = (Array.isArray(history) ? history : []).filter((h) => h !== keyword);
				setHistory(newHistory);
				onSaveHistory(newHistory);
			} else setHistory(removeHistoryItem(historyKey, keyword));
		}, [
			history,
			historyKey,
			onSaveHistory
		]),
		clearAllHistory: useCallback(() => {
			if (onSaveHistory) {
				setHistory([]);
				onSaveHistory([]);
			} else {
				clearHistory(historyKey);
				setHistory([]);
			}
		}, [historyKey, onSaveHistory]),
		reloadHistory
	};
};
//#endregion
export { useSearchHistory };
