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

export default ({ propValue, config, onChange = () => {} }) => {
  const { name, label } = config;
  const [inputSrc, setInputSrc] = useState();

  const onInputChange = ({ target: { value } }) => {
    setInputSrc(value);
    onChange(name, value);
  };

  useEffect(() => {
    const imageSrc = findValueByNamePath(name, propValue);
    setInputSrc(imageSrc);
  }, [propValue]);

  return (
    <div className="drawer-item-image">
      <Form.Item label={label}>
        <div className="image-cell">
          <Selector
            src={inputSrc}
            onChange={e => onInputChange({ target: { value: e } })}
          />
          <div className="image-cell__input">
            <Input value={inputSrc} onChange={onInputChange} />
          </div>
        </div>
      </Form.Item>
    </div>
  );
};
