import React, { useState, useEffect } from 'react';
import { View, StyleSheet, Alert } from 'react-native';
import { useRoute, useNavigation } from '@react-navigation/native';
import { RouteProp } from '@react-navigation/native';
import TaskForm from '../components/TaskForm';
import BottomActionBar from '../components/BottomActionBar';
import { Task } from '../types/task';

import { MOCK_TASKS } from '../data/mockData'; 

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

type TaskEditRouteProp = RouteProp<RootStackParamList, 'TaskEdit'>;

export default function TaskEditScreen() {
  const route = useRoute<TaskEditRouteProp>();
  const navigation = useNavigation();
  const { taskId } = route.params;

  const [task, setTask] = useState<Task | null>(null);
  const [isModified, setIsModified] = useState(false);

  useEffect(() => {
    // 根据taskId从模拟数据中查找任务
    const foundTask = MOCK_TASKS.find(t => t.id === taskId);
    if (foundTask) {
      setTask(foundTask);
    }
  }, [taskId]);

  const handleTaskChange = (updatedTask: Task) => {
    setTask(updatedTask);
    if (!isModified) {
      setIsModified(true);
    }
  };

  const handleSave = () => {
    // 在这里处理保存逻辑，比如调用API
    Alert.alert('已保存', `任务 "${task?.name}" 已被保存。`);
    setIsModified(false);
  };

  if (!task) {
    return null; // 或者显示一个加载指示器
  }

  return (
    <View style={styles.container}>
      <TaskForm task={task} onTaskChange={handleTaskChange} />
      <BottomActionBar
        onRun={() => Alert.alert('运行', '开始运行任务...')}
        onSave={handleSave}
        onUndo={() => Alert.alert('撤销', '撤销更改...')}
        onRestore={() => Alert.alert('恢复', '恢复到初始状态...')}
        onBack={() => navigation.goBack()}
        isSaveDisabled={!isModified}
      />
    </View>
  );
}

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