import { useState } from "react";
import { TaskDefinition } from "../services/WorkflowTemplateService";
import { TaskCoreEditor } from "./CapabilityEditors/TaskCoreEditor";

export interface TaskValidationResult {
  isValid: boolean;
  errors: Record<string, string>;
}

interface TaskEditorProps {
  task: TaskDefinition;
  allTasks: TaskDefinition[];
  allowedTasks: TaskMetadata[];
  onChange: (updatedTask: TaskDefinition) => void;
  onValidate: (taskId: string, isValid: boolean) => void;
}

export const TaskEditor: React.FC<TaskEditorProps> = ({
  task,
  allTasks,
  allowedTasks,
  onChange,
  onValidate,
}) => {
  const [validationMap, setValidationMap] = useState<
    Record<string, TaskValidationResult>
  >({});

  const onCapabilityValidate = (
    capabilityName: string,
    result: TaskValidationResult,
  ) => {
    setValidationMap((prev) => {
      const updated = { ...prev, [capabilityName]: result };

      const allValid = Object.values(updated).every((r) => r.isValid);

      onValidate(task.config.guid as string, allValid);

      return updated;
    });
  };

  return (
    <>
      <TaskCoreEditor
        task={task}
        allowedTasks={allowedTasks}
        allTasks={allTasks}
        onChange={onChange}
        onValidate={(result) => onCapabilityValidate("core", result)}
      />
    </>
  );
};
