import React, { useState, useEffect } from 'react';
import { View, StyleSheet, Alert, ScrollView } from 'react-native';
import { useRoute, useNavigation } from '@react-navigation/native';
import { RouteProp } from '@react-navigation/native';
import { useTasks } from '../context/TasksContext';
import TaskForm from '../components/TaskForm';
import BottomActionBar from '../components/BottomActionBar';
import { Task } from '../types/task';
import { Dialog, Card } from '@rneui/themed';

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 { getTaskById, updateTask, runTask, tasks } = useTasks();

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

  useEffect(() => {
    const taskData = getTaskById(taskId);
    if (taskData) {
      setTask(taskData);
      setOriginalTask(taskData);
    }
  }, [taskId, getTaskById, tasks]); // Add tasks to dependency array

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

  const handleSave = () => {
    if (task) {
      updateTask(task);
      setOriginalTask(task);
      setIsModified(false);
      Alert.alert('已保存', `任务 "${task.name}" 已被保存。`);
    }
  };

  const handleRun = () => {
    if (task) {
      runTask(task.id);
      navigation.goBack();
    }
  };

  const handleUndo = () => {
    setTask(originalTask);
    setIsModified(false);
  };

  const handleRestore = () => {
    setTask(originalTask);
    setIsModified(false);
  };

  if (!task) {
    return (
      <Dialog isVisible={true}>
        <Dialog.Loading />
      </Dialog>
    );
  }

  return (
    <View style={styles.container}>
      <ScrollView>
        <Card containerStyle={styles.card}>
          <TaskForm task={task} onTaskChange={handleTaskChange} />
        </Card>
      </ScrollView>
      <BottomActionBar
        onRun={handleRun}
        onSave={handleSave}
        onUndo={handleUndo}
        onRestore={handleRestore}
        onBack={() => navigation.goBack()}
        isSaveDisabled={!isModified}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f0f2f5',
  },
  card: {
    borderRadius: 8,
    margin: 10,
  },
});
