import { Alert, StyleSheet, TouchableOpacity, View } from 'react-native'
import { Ionicons } from '@expo/vector-icons'
import { useSummaryData } from '../src/features/summary/useSummaryData'
import { FilterBar } from '../src/features/summary/FilterBar'
import { SummaryStats } from '../src/features/summary/SummaryStats'
import { SummaryList } from '../src/features/summary/SummaryList'
import { exportWithPhotos } from '../src/features/summary/exportData'
import type { FloorNumber } from '@repo/types'
import { Stack, useFocusEffect } from 'expo-router'
import { useCallback } from 'react'

export default function SummaryScreen() {
  const { rows, filter, setFilter, refresh } = useSummaryData()

  useFocusEffect(useCallback(() => {
    refresh()
  }, []))

  async function handleExport() {
    try {
      await exportWithPhotos(rows)
    } catch (err) {
      Alert.alert('导出失败', String(err))
    }
  }

  return (
    <>
      <Stack.Screen
        options={{
          headerRight: () => (
            <TouchableOpacity onPress={handleExport} style={styles.exportBtn}>
              <Ionicons name="share-outline" size={22} color="#10B981" />
            </TouchableOpacity>
          ),
        }}
      />
      <View style={styles.container}>
        <SummaryStats rows={rows} />
        <FilterBar
          floor={filter.floor}
          keyword={filter.keyword}
          onFloorChange={(floor) =>
            setFilter((f) => ({ ...f, floor: floor as FloorNumber | 0 }))
          }
          onKeywordChange={(keyword) => setFilter((f) => ({ ...f, keyword }))}
        />
        <SummaryList rows={rows} />
      </View>
    </>
  )
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: '#fff' },
  exportBtn: { paddingHorizontal: 8 },
})
