import { useCallback, useEffect, useState } from 'react'
import AsyncStorage from '@react-native-async-storage/async-storage'

const STORAGE_KEY = '@searchHistory'
const MAX_HISTORY_LENGTH = 10

interface UseSearchHistoryReturn {
    history: string[]
    addToHistory: (keyword: string) => Promise<void>
    removeFromHistory: (keyword: string) => Promise<void>
    clearHistory: () => Promise<void>
    isLoading: boolean
}

export function useSearchHistory(): UseSearchHistoryReturn {
    const [history, setHistory] = useState<string[]>([])
    const [isLoading, setIsLoading] = useState(true)

    useEffect(() => {
        loadHistory()
    }, [])

    const loadHistory = useCallback(async () => {
        try {
            const stored = await AsyncStorage.getItem(STORAGE_KEY)
            setHistory(stored ? JSON.parse(stored) : [])
        } catch {
            setHistory([])
        } finally {
            setIsLoading(false)
        }
    }, [])

    const saveHistory = useCallback(async (newHistory: string[]) => {
        try {
            await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(newHistory))
            setHistory(newHistory)
        } catch {
            setHistory(newHistory)
        }
    }, [])

    const addToHistory = useCallback(
        async (keyword: string) => {
            const trimmed = keyword.trim()
            if (!trimmed) return

            const filtered = history.filter((item) => item !== trimmed)
            const updated = [trimmed, ...filtered].slice(0, MAX_HISTORY_LENGTH)
            await saveHistory(updated)
        },
        [history, saveHistory]
    )

    const removeFromHistory = useCallback(
        async (keyword: string) => {
            const updated = history.filter((item) => item !== keyword)
            await saveHistory(updated)
        },
        [history, saveHistory]
    )

    const clearHistory = useCallback(async () => {
        await saveHistory([])
    }, [saveHistory])

    return {
        history,
        addToHistory,
        removeFromHistory,
        clearHistory,
        isLoading,
    }
}
