import React, { useState, useEffect } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Form, Button, Divider } from 'antd';
import { v4 } from 'uuid';
import { FormilyType, FormilyTypeSource, FormilyData } from './interface';
import { allItems } from './constant';
import { FormilyContext } from './context';
import Item, { FormilyItemProps } from './item';
import Render from './render';
import styles from './index.less';

interface FormilyProps
  extends Pick<FormilyItemProps, 'nameFormItem' | 'optionsFormItem'> {
  items?: FormilyType[] | 'all';
  list?: FormilyData[];
}

interface FormilyTypeFC extends React.FC<FormilyProps> {
  Render: typeof Render;
}

const { List } = Form;

const Formily: FormilyTypeFC = ({
  list = [],
  items,
  nameFormItem,
  optionsFormItem,
}) => {
  const [formilyTypeSource, setFormilyTypeSource] = useState<FormilyTypeSource>(
    {},
  );
  const optionKeys: FormilyType[] = items === 'all' ? allItems : items || [];

  useEffect(() => {
    const map = {};
    list.forEach((item, index) => {
      map[index] = item.type;
    });
    setFormilyTypeSource(map);
  }, [JSON.stringify(list)]);

  return (
    <List name="template">
      {(fields, { add, remove }) => {
        return (
          <FormilyContext.Provider
            value={{
              fields,
              formilyTypes: optionKeys,
              formilyTypeSource,
              setFormilyTypeSource,
              add,
              remove,
            }}
          >
            <div className={styles.fieldConfig}>
              {fields.map(field => (
                <div key={field.key}>
                  <Item
                    field={field}
                    nameFormItem={nameFormItem}
                    optionsFormItem={optionsFormItem}
                  />
                  {fields.length !== field.key + 1 && <Divider dashed />}
                </div>
              ))}

              <Form.Item
                key="add"
                style={{ marginTop: fields.length ? 0 : 24 }}
                wrapperCol={{ span: 24 }}
              >
                <Button
                  type="dashed"
                  onClick={() => {
                    add({ id: v4() });
                  }}
                  block
                >
                  <PlusOutlined /> 添加字段
                </Button>
              </Form.Item>
            </div>
          </FormilyContext.Provider>
        );
      }}
    </List>
  );
};

Formily.defaultProps = {
  items: ['inputs', 'selects', 'multiSelects', 'dates', 'dateBetweens'],
};

Formily.Render = Render;

export * from './utils';
export * from './interface';
export default Formily;
