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 { useTasks } from '../context/TasksContext';
import TaskForm from '../components/TaskForm';
import BottomActionBar from '../components/BottomActionBar';
import { Task } from '../types/task';
import { Dialog } from '@rneui/themed';

type RootStackParamList = {
  TaskEdit: { task: Task };
};

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

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

  const { updateTask, runTask } = useTasks();

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

  useEffect(() => {
    if (initialTask) {
      setTask(initialTask);
      setOriginalTask(initialTask);
    }
  }, [initialTask]);

  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}>
      <TaskForm task={task} onTaskChange={handleTaskChange} />
      <BottomActionBar
        onRun={handleRun}
        onSave={handleSave}
        onUndo={handleUndo}
        onRestore={handleRestore}
        onBack={() => navigation.goBack()}
        isSaveDisabled={!isModified}
      />
    </View>
  );
}

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