import React, { useEffect, useState, useMemo } from 'react';
import classNames from '@pansy/classnames';
import { PlusCircleOutlined, MinusCircleOutlined } from '@ant-design/icons';
import { v4 } from 'uuid';
import { Input } from 'antd';
import { InputProps } from 'antd/es/input';
import { FormListOperation } from 'antd/es/form/FormList';
import { Form } from 'antd';
import styles from './options.less';

interface OptionsProps {
  name: string | number | (string | number)[];
}

export interface OptionType {
  id: string;
  name: string | undefined;
}

interface InputPlusProps
  extends Omit<InputProps, 'value' | 'onChange'>,
    Partial<FormListOperation> {
  value?: OptionType;
  fields?: any;
  field?: any;
  onChange?: (value?: OptionType) => void;
}

const formLayout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 20 }
};

const InputPlus: React.FC<InputPlusProps> = ({
  value,
  add,
  remove,
  move,
  fields,
  field,
  onChange,
  ...rest
}) => {
  const [val, setValue] = useState<string>();

  useEffect(() => {
    setValue(value?.name);
  }, [JSON.stringify(value)]);

  const handleChange = (e: any) => {
    onChange?.(value ? { ...value, name: e.target.value } : undefined);
  };

  const input = useMemo(() => {
    return <Input value={val} onChange={handleChange} {...(rest as any)} />;
  }, [val]);

  return (
    <div className={styles.item}>
      {input}
      <PlusCircleOutlined
        onClick={() => {
          add?.({ id: v4(), name: '' }, field?.name + 1);
        }}
      />
      <MinusCircleOutlined
        className={fields.length <= 2 ? styles.disabled : undefined}
        onClick={() => {
          if (fields.length > 2) {
            remove?.(field.name);
          }
        }}
      />
    </div>
  );
};

const Options: React.FC<OptionsProps> = ({ name }) => {
  return (
    <Form.List name={name}>
      {(fields, { add, remove }) => {
        if (fields.length === 0) {
          setTimeout(() => {
            add({ id: v4(), name: '' });
            add({ id: v4(), name: '' });
          }, 200);
        }

        return (
          <>
            {fields.map((field, index) => (
              <Form.Item
                label={index === 0 ? '选项' : <span />}
                {...formLayout}
                rules={[
                  { required: true, message: '' },
                  () => ({
                    validator(_, value: { id: string; name: string }) {
                      if (value?.name) {
                        return Promise.resolve();
                      }
                      return Promise.reject('选项内容不能为空');
                    }
                  })
                ]}
                className={classNames({
                  [`${styles.hiddenRequired}`]: index !== 0
                })}
                {...field}
              >
                <InputPlus
                  add={add}
                  remove={remove}
                  field={field}
                  fields={fields}
                  placeholder="输入选项名称"
                />
              </Form.Item>
            ))}
          </>
        );
      }}
    </Form.List>
  );
};

export default Options;
