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

import SearchBar from '@/components/SearchBar'
import WorksGallery, { type Category, type WorkItem } from '@/components/WorksGallery'

// 模拟搜索结果数据
const mockSearchResults: WorkItem[] = [
    { id: 1, date: new Date(2025, 10, 28), duration: '00:05', category: '写真' },
    { id: 2, date: new Date(2025, 10, 28), duration: '00:05', category: '写真' },
    { id: 3, date: new Date(2025, 10, 27), duration: '00:05', category: '写真' },
    { id: 4, date: new Date(2025, 10, 27), duration: '00:05', category: '写真' },
    { id: 5, date: new Date(2025, 10, 27), duration: '00:05', category: '写真' },
    { id: 6, date: new Date(2025, 10, 27), duration: '00:05', category: '写真' },
]

export default function SearchWorksResultsScreen() {
    const { t } = useTranslation()
    const router = useRouter()
    const params = useLocalSearchParams()
    const [searchText, setSearchText] = useState((params.q as string) || '')
    
    const categories: Category[] = [
        t('worksList.all') as Category,
        t('worksList.pets') as Category,
        t('worksList.portrait') as Category,
        t('worksList.together') as Category,
    ]
    
    const [selectedCategory, setSelectedCategory] = useState<Category>(categories[0])

    // 根据分类过滤结果
    const filteredWorks = selectedCategory === categories[0]
        ? mockSearchResults
        : mockSearchResults.filter(work => work.category === selectedCategory)

    // 按日期分组
    const filteredGroupedWorks = filteredWorks.reduce((acc, work) => {
        // 使用日期作为分组键，格式化为 YYYY-MM-DD 以便正确分组
        const dateKey = work.date instanceof Date 
            ? work.date.toISOString().split('T')[0]
            : new Date(work.date).toISOString().split('T')[0]
        
        if (!acc[dateKey]) {
            acc[dateKey] = []
        }
        acc[dateKey].push(work)
        return acc
    }, {} as Record<string, WorkItem[]>)

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

            {/* Top Bar with Search */}
            <SearchBar
                searchText={searchText}
                onSearchTextChange={setSearchText}
                onSearch={(text) => {
                    router.push({
                        pathname: '/searchWorksResults',
                        params: { q: text },
                    })
                }}
                onBack={() => router.back()}
                placeholder={t('search.searchWorks')}
                marginBottom={0}
                readOnly={true}
                onInputPress={() => {
                    router.push({
                        pathname: '/searchWorks',
                        params: { q: searchText },
                    })
                }}
                onClearPress={() => {
                    router.push({
                        pathname: '/searchWorks',
                        params: { q: '' },
                    })
                }}
            />

            <WorksGallery
                categories={categories}
                selectedCategory={selectedCategory}
                onCategoryChange={setSelectedCategory}
                groupedWorks={filteredGroupedWorks}
                onWorkPress={(id) => {
                    router.push({
                        pathname: '/generationRecord' as any,
                        params: { id: id.toString() },
                    })
                }}
            />
        </SafeAreaView>
    )
}

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

