import React, { useState } from 'react';
import classNames from 'classnames/bind';
import styles from './Feature.scss';
import Input from './Input';

const cx = classNames.bind(styles);

interface IOwnProps {
  feature: IFeature[];
  setFeature: (feature: IFeature[]) => void;
  createNewFeature: () => void;
  index: number;
  isResalePage: boolean;
};

export interface IFeature {
  key: string;
  value: string;
}

const Feature: React.FC<IOwnProps> = ({ feature, setFeature, createNewFeature, index, isResalePage }) => {
  const [key, setKey] = useState<string>('');
  const [value, setValue] = useState<string>('');
  const [isCreateNewFeature, setIsCreateNewFeature] = useState<boolean>(false);

  const createNew = () => {
    createNewFeature();
    setIsCreateNewFeature(true);
  };

  const handleChangeKey = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (value && !isCreateNewFeature) {
      createNew();
    }
    setKey(e.target.value);
  };

  const handleChangeValue = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (key && !isCreateNewFeature) {
      createNew();
    }

    setValue(e.target.value);
  };

  const handleBlur = () => {
    const list = [...feature];

    list[index].key = key;
    list[index].value = value;

    setFeature(list);
  };

  return (
    <>
      <Input className={cx('input')} placeholder={'예) 사이즈'} onChange={handleChangeKey} onBlur={handleBlur} disabled={isResalePage} value={key} />
      <Input className={cx('input')} placeholder={'예) M'} onChange={handleChangeValue} onBlur={handleBlur} disabled={isResalePage} value={value} />
    </>
  );
};

export default Feature;
