import React, { useEffect, useState } from "react";
import templateVersionsService, {
  CreateWorkflowTemplateVersion,
  TaskDefinition,
  TaskMetadata,
} from "../services/WorkflowTemplateService";
import TaskList from "./TaskList";
import { TaskEditor } from "./TasksEditor";

interface TasksTabProps {
  data: CreateWorkflowTemplateVersion;
  errors: Record<string, string>;
  isEditMode: boolean;
  onTasksChange: (name: string, value: TaskDefinition[]) => void;
  onValidate: (taskId: string, isValid: boolean) => void;
  taskValidation: Record<string, boolean>;
}

const TasksTab: React.FC<TasksTabProps> = ({
  data,
  errors,
  isEditMode,
  onTasksChange,
  onValidate,
  taskValidation,
}) => {
  const tasks = data.tasks;
  const [selectedTask, setSelectedTask] = useState<TaskDefinition | null>(null);
  const [tasksMetadata, setTasksMetadata] = React.useState<TaskMetadata[]>([]);

  useEffect(() => {
    const fetchTaskMetadata = async () => {
      const meta = await templateVersionsService.getTaskMetadata("GeneralTask");
      setTasksMetadata(meta);
    };

    fetchTaskMetadata();
  }, []);

  useEffect(() => {
    // Don't override user selection
    if (selectedTask) return;

    if (tasks.length === 0) {
      setSelectedTask(null);
      return;
    }

    // Find first invalid task
    const firstInvalid = tasks.find(
      (t) => taskValidation[t.config.guid as string] === false,
    );

    if (firstInvalid) {
      setSelectedTask(firstInvalid);
      return;
    }

    // Otherwise select first task
    setSelectedTask(tasks[0]);
  }, [tasks, taskValidation, selectedTask]);

  const handleTasksChange = (newTasks: TaskDefinition[]) => {
    // Update the parent form state
    onTasksChange("tasks", newTasks);
  };

  return (
    <div className="two-column-grid">
      <div className="fit-content-width">
        <TaskList
          tasks={tasks}
          validTasksList={taskValidation}
          tasksMetadata={tasksMetadata}
          onChange={handleTasksChange}
          selectedTask={selectedTask}
          onSelectTask={setSelectedTask}
        />
      </div>
      {selectedTask && (
        <TaskEditor
          tasksMetadata={tasksMetadata}
          task={selectedTask}
          tasks={tasks}
          onChange={(updatedTask) => {
            const newTasks = tasks.map((t) =>
              t.config.guid === updatedTask.config.guid ? updatedTask : t,
            );

            handleTasksChange(newTasks);

            // Use the updated object from the array, not the raw updatedTask
            const updatedFromArray = newTasks.find(
              (t) => t.config.guid === updatedTask.config.guid,
            );

            setSelectedTask(updatedFromArray!);
          }}
          onValidate={onValidate}
        />
      )}
    </div>
  );
};

export default TasksTab;
