import React, { useState, useEffect } from 'react';
import {
  View,
  StyleSheet,
  Alert,
  ScrollView,
  ActivityIndicator,
} 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';

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, fetchTaskDetail } =
    useTasks();

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

  useEffect(() => {
    const loadTask = async () => {
      let taskData = getTaskById(taskId);
      if (taskData && !taskData.detail) {
        await fetchTaskDetail(taskId);
        // Re-fetch task data after details are loaded
        taskData = getTaskById(taskId);
      }
      if (taskData) {
        setTask(taskData);
        setOriginalTask(taskData);
      }
    };
    loadTask();
  }, [taskId, getTaskById, tasks, fetchTaskDetail]);

  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 (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#00ff00" />
      </View>
    );
  }

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

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1a1a1a', // 深色背景
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#1a1a1a',
  },
  scrollContainer: {
    padding: 16,
  },
});
