import React, { useState, useEffect } from 'react';
import { type Step } from "../types/Recipe";

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.instructions}`
    ).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 = lines.map((line, idx) => {
      return { idx: idx + 1, instructions: line }
    })

    if (onChange) onChange(parsedSteps);
  };

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

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

  return (
    <div>
      <p>Please enter each step on a new line</p>
      <textarea
        rows={4}
        cols={50}
        value={textValue}
        onChange={handleInputChange}
        onKeyDown={handleKeyDown}
        onBlur={handleBlur}
        placeholder="Enter ingredients separated by newline..."
      />
    </div>
  );
};

export default AddBulkSteps;
