import React, { useState, useEffect } from 'react';
import { Form, Input } from 'antd';
import { findValueByNamePath } from '../../utils';

export default ({ node, propKey, config, onChangePathValue }) => {
  const { label, name } = config;
  const [inputValue, setInputValue] = useState();

  const handleChange = ({ target: { value } }) => {
    setInputValue(value);
    onChangePathValue({ path: name, value });
  };

  useEffect(() => {
    const nextValue = findValueByNamePath(name, node[propKey]);
    setInputValue(nextValue);
  }, [node[propKey], name]);

  return (
    <Form.Item label={label}>
      <Input value={inputValue} onChange={handleChange} />
    </Form.Item>
  );
};
