import React, { useLayoutEffect, useState, useCallback } from 'react';
import {
  View,
  StyleSheet,
  FlatList,
  TouchableOpacity,
  ActivityIndicator,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import { useTasks } from '../context/TasksContext';
import TaskCard from '../components/TaskCard';

type RootStackParamList = {
  TaskList: undefined;
  TaskEdit: { taskId: string };
};

type TaskListNavigationProp = StackNavigationProp<
  RootStackParamList,
  'TaskList'
>;

export default function TaskListScreen() {
  const { tasks, refreshTasks } = useTasks();
  const navigation = useNavigation<TaskListNavigationProp>();
  const [isRefreshing, setIsRefreshing] = useState(false);

  const handleRefresh = useCallback(async () => {
    setIsRefreshing(true);
    try {
      await refreshTasks();
    } catch (error) {
      console.error('刷新任务失败:', error);
    } finally {
      setIsRefreshing(false);
    }
  }, [refreshTasks]);

  useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: () => (
        <TouchableOpacity onPress={handleRefresh} style={{ marginRight: 15 }}>
          {isRefreshing ? (
            <ActivityIndicator size="small" color="#ffffff" />
          ) : (
            <MaterialIcons name="refresh" size={24} color="#ffffff" />
          )}
        </TouchableOpacity>
      ),
    });
  }, [navigation, isRefreshing, handleRefresh]);

  const handlePressTask = (id: string) => {
    navigation.navigate('TaskEdit', { taskId: id });
  };

  const renderItem = ({ item }: { item: (typeof tasks)[0] }) => (
    <TaskCard task={item} onPress={handlePressTask} />
  );

  return (
    <View style={styles.container}>
      <FlatList
        data={tasks}
        renderItem={renderItem}
        keyExtractor={item => item.id}
        ItemSeparatorComponent={() => <View style={styles.separator} />}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1a1a1a', // 深色背景
  },
  separator: {
    height: 1,
    backgroundColor: '#333', // 分隔线颜色
    marginLeft: 16,
  },
});
