import Input, { InputType } from "../../../../components/common/Input";
import { TaskDefinition } from "../services/WorkflowTemplateService";

export const renderTaskField = (
  task: TaskDefinition,
  onChange: (updated: TaskDefinition) => void,
  field: string,
  label: string,
  type: InputType,
  errors: Record<string, string>,
  placeholder?: string,
  maxLength?: number,
  extraProps?: {
    options?: { value: string; label: string }[];
  },
) => {
  const handleChange = (
    e: React.ChangeEvent<
      HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement
    >,
  ) => {
    const newValue = e.target.value;

    onChange({
      ...task,
      config: {
        ...task.config,
        [field]: newValue,
      },
    });
  };

  return renderTaskInput(
    field,
    label,
    task.config[field],
    errors ? errors[field] : null,
    type,
    handleChange,
    false,
    placeholder ?? "",
    maxLength ?? 0,
    extraProps,
  );
};

export const renderTaskInput = (
  name: string,
  label: string,
  value: string | number | readonly string[] | undefined,
  error: string | undefined,
  type: InputType = InputType.text,
  onChange: (
    e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>,
  ) => void,
  readOnly: boolean = false,
  placeholder: string = "",
  maxLength: number = 0,
  extraProps?: {
    options?: { value: string; label: string }[];
  },
) => {
  const normalisedValue =
    type === InputType.multiselect
      ? ((value as string[]) ?? [])
      : (value ?? "");

  return (
    <Input
      includeLabel={true}
      type={type}
      name={name}
      label={label}
      value={normalisedValue}
      error={error}
      maxLength={maxLength}
      onChange={onChange}
      readOnly={readOnly}
      placeHolder={placeholder}
      {...extraProps}
    />
  );
};
