import { useState, useEffect } from 'react'
import {
    View,
    StyleSheet,
    StatusBar as RNStatusBar,
    RefreshControl,
} from 'react-native'
import { StatusBar } from 'expo-status-bar'
import { SafeAreaView } from 'react-native-safe-area-context'
import { useRouter, useLocalSearchParams } from 'expo-router'

import SearchResultsGrid from '@/components/SearchResultsGrid'
import SearchBar from '@/components/SearchBar'
import { useTemplates, useSearchHistory } from '@/hooks'

export default function SearchResultsScreen() {
    const router = useRouter()
    const params = useLocalSearchParams()
    const [searchText, setSearchText] = useState((params.q as string) || '')
    const [refreshing, setRefreshing] = useState(false)

    // 使用 useTemplates hook 进行搜索
    const { templates, loading, error, execute, refetch } = useTemplates()

    // 使用搜索历史 hook
    const { addToHistory } = useSearchHistory()

    // 当搜索关键词变化时，执行搜索
    useEffect(() => {
        if (params.q && typeof params.q === 'string') {
            const query = params.q.trim()
            setSearchText(query)
            if (query) {
                // 执行搜索
                execute({ search: query, limit: 50, sortBy: 'createdAt', sortOrder: 'desc', page: 1 })
                // 添加到搜索历史
                addToHistory(query)
            }
        }
    }, [params.q, execute, addToHistory])

    // 处理下拉刷新
    const handleRefresh = async () => {
        setRefreshing(true)
        if (searchText) {
            await refetch()
        }
        setRefreshing(false)
    }

    // 将模板数据转换为搜索结果格式
    const searchResults = templates.map(template => ({
        id: template.id,
        title: template.title || template.titleEn || '',
        image: { uri: template.previewUrl || template.coverImageUrl || '' },
        previewUrl: template.previewUrl,
        coverImageUrl: template.coverImageUrl,
        aspectRatio: template.aspectRatio ? parseFloat(template.aspectRatio as string) : undefined,
    }))

    return (
        <SafeAreaView style={styles.container} edges={['top']}>
            <StatusBar style="light" />
            <RNStatusBar barStyle="light-content" />

            <SearchBar
                searchText={searchText}
                onSearchTextChange={setSearchText}
                onSearch={(text) => {
                    router.push({
                        pathname: '/searchTemplate',
                        params: { q: text, focus: 'true' },
                    })
                }}
                onBack={() => router.back()}
                readOnly={true}
                onInputPress={() => {
                    router.push({
                        pathname: '/searchTemplate',
                        params: { q: searchText, focus: 'true' },
                    })
                }}
                onClearPress={() => {
                    router.push({
                        pathname: '/searchTemplate',
                        params: { q: '', focus: 'true' },
                    })
                }}
                marginBottom={12}
            />

            <SearchResultsGrid
                results={searchResults}
                loading={loading}
            />
        </SafeAreaView>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#090A0B',
    },
})
