import React from "react";
import {
  TaskDefinition,
  TaskMetadata,
} from "../services/WorkflowTemplateService";
import AddTaskButton from "./AddTaskButton";
import { SelectableList } from "../../../../components/common/SelectableList";
import { faExclamationCircle } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";

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

const TaskList: React.FC<TaskListProps> = ({
  tasks,
  validTasksList,
  allowedTasks,
  onChange,
  selectedTask,
  onSelectTask,
}) => {
  const handleAddTask = (selectedType: TaskMetadata) => {
    const newTask: TaskDefinition = {
      type: selectedType.taskType,

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

    //if (tasks.length === 0) {
    onSelectTask(newTask);
    //}
    onChange([...tasks, newTask]);
  };

  return (
    <div>
      <AddTaskButton allowedTasks={allowedTasks} onAdd={handleAddTask} />

      <SelectableList
        items={tasks}
        selectedValue={selectedTask}
        renderLabel={(x) => (
          <>
            {x.config.name as string}

            {validTasksList[x.config.guid as string] === false && (
              <span className="error-icon">
                <FontAwesomeIcon icon={faExclamationCircle} />
              </span>
            )}
          </>
        )}
        onSelect={(item) => onSelectTask(item)}
      />
    </div>
  );
};

export default TaskList;
