import React from "react";
import {
  TaskDefinition,
  TaskMetadata,
} from "../services/WorkflowTemplateService";
import AddTaskButton from "./AddTaskButton";
import { SelectableList } from "../../../../components/common/SelectableList";
import { sortTasksTopologically } from "./workflowGraphUtils";
import { useCapabilityDefaults, validateTask } from "./useCapabilityDefaults";
import ValidationErrorIcon from "../../../../components/validationErrorIcon";

interface TaskListProps {
  tasks: TaskDefinition[];
  validTasksList: Record<string, boolean>;
  tasksMetadata: TaskMetadata[];
  onChange: (tasks: TaskDefinition[]) => void;
  selectedTask: TaskDefinition | null;
  onSelectTask: (task: TaskDefinition | null) => void;
  onValidate: (taskId: string, isValid: boolean) => void;
}

const TaskList: React.FC<TaskListProps> = ({
  tasks,
  validTasksList,
  tasksMetadata,
  onChange,
  selectedTask,
  onSelectTask,
  onValidate,
}) => {
  const runDefaults = useCapabilityDefaults(tasksMetadata);

  const handleAddTask = (selectedType: TaskMetadata) => {
    const newTask: TaskDefinition = {
      type: selectedType.taskType,

      config: {
        guid: crypto.randomUUID(),
      },
    };

    //Assign the default values for the task here.
    selectedType.capabilities.forEach((capability) => {
      runDefaults(capability, newTask, tasks);
    });

    const updatedTasks = [...tasks, newTask];
    const errors = validateTask(newTask, updatedTasks, tasksMetadata);

    onValidate(newTask.config.guid as string, Object.keys(errors).length === 0);

    onChange(updatedTasks);
    onSelectTask(newTask);
  };

  const sortedTasks = sortTasksTopologically(tasks);

  return (
    <div className="task-list-container">
      <div className="task-list-header">
        <AddTaskButton tasksMetadata={tasksMetadata} onAdd={handleAddTask} />
      </div>

      <div className="task-list-content">
        <SelectableList
          items={sortedTasks}
          selectedValue={selectedTask}
          renderLabel={(x) => {
            if (x) {
              return (
                <>
                  {x.config.name as string}

                  {
                    <ValidationErrorIcon
                      visible={
                        validTasksList[x.config.guid as string] === false
                      }
                    />
                  }
                </>
              );
            } else return <></>;
          }}
          onSelect={(item) => onSelectTask(item)}
        />
      </div>
    </div>
  );
};

export default TaskList;
