import React, { useState, useEffect } from 'react';
import { StyleSheet, ScrollView, Text, View } from 'react-native';
import { Input } from '@rneui/themed';
import { Task, RobotAction, InputParam } from '../types/task';

interface TaskFormProps {
  task: Task;
  onTaskChange: (updatedTask: Task) => void;
}

const TaskForm: React.FC<TaskFormProps> = ({ task, onTaskChange }) => {
  useEffect(() => {
    console.log('TaskForm task prop updated:', task);
  }, [task]);

  const handleParamChange = (field: string, value: string | RobotAction) => {
    const currentParam = task.parameters[field] || {};
    const updatedTask = {
      ...task,
      parameters: {
        ...task.parameters,
        [field]: {
          ...currentParam,
          value: value,
        },
      },
    };
    onTaskChange(updatedTask);
  };

  const renderFormInput = (param: InputParam) => {
    const parameter = task.parameters?.[param.name];
    const value = parameter?.value || param.defaultValue;

    switch (param.type.toLowerCase()) {
      case 'string':
        return (
          <Input
            key={param.name}
            label={param.label}
            value={value as string}
            onChangeText={text => handleParamChange(param.name, text)}
            placeholder={param.remark}
          />
        );
      default:
        return (
          <Input
            key={param.name}
            label={param.label}
            value={value as string}
            onChangeText={text => handleParamChange(param.name, text)}
            placeholder={param.remark}
          />
        );
    }
  };

  return (
    <ScrollView contentContainerStyle={styles.container}>
      <Input
        label="任务名称"
        value={task.name}
        onChangeText={text => onTaskChange({ ...task, name: text })}
      />

      {task.detail && task.detail.inputParams ? (
        task.detail.inputParams.map(param => renderFormInput(param))
      ) : (
        <View style={styles.loadingContainer}>
          <Text>正在加载任务参数...</Text>
        </View>
      )}
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    padding: 16,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
});

export default TaskForm;
