import React, { useState, useEffect } from 'react';

interface Step {
  step_number: number;
  instruction: string;
}

interface AddBulkStepsProps {
  steps: Step[];
  onChange?: (steps: Step[]) => void;
}

const AddBulkSteps: React.FC<AddBulkStepsProps> = ({ steps, onChange }) => {
  const [textValue, setTextValue] = useState<string>('');

  useEffect(() => {
    const textRepresentation = steps.map(step =>
      `${step.instruction}`
    ).join('\n');
    setTextValue(textRepresentation);
  }, [steps]);

  const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setTextValue(e.target.value);
  };


  const parseAndUpdate = (value: string) => {
    const lines = value.split('\n').filter(line => line.trim() !== '');

    const parsedSteps: Step[] = lines.map((line, idx) => {
      return { step_number: idx + 1, instruction: line }
    })

    if (onChange) onChange(parsedSteps);
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === 'Enter') {
      parseAndUpdate(textValue);
    }
  };

  const handleBlur = () => {
    parseAndUpdate(textValue);
  };

  return (
    <div>
      <h3 className="text-xl font-bold">Steps:</h3>
      <textarea
        rows={8}
        value={textValue}
        onChange={handleInputChange}
        onKeyDown={handleKeyDown}
        onBlur={handleBlur}
        placeholder="Enter steps separated by new line"
        className="mb-4 p-2 border border-gray-300 rounded w-full"
      />
    </div>
  );
};

export default AddBulkSteps;
