import React, { useContext } from 'react';
import ArabicChinese from '@pansy/arabic-chinese-converter';
import { Typography, Form, Input, Radio, Checkbox } from 'antd';
import { FormItemProps } from 'antd/es/form/FormItem';
import { RadioChangeEvent } from 'antd/es/radio/interface';
import { TextLink } from '@sensoro/sensoro-design';
import Options from './options';
import { formilyConfig } from './constant';
import { FormilyContext, FieldData } from './context';
import styles from './index.less';

export interface FormilyItemProps {
  field: FieldData;
  nameFormItem?: FormItemProps;
  optionsFormItem?: FormItemProps;
}

const { Group } = Radio;
const { Title } = Typography;
const arabicChinese = new ArabicChinese();
const formLayout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 20 }
};

const FormilyItem: React.FC<FormilyItemProps> = ({
  field,
  nameFormItem = {},
  optionsFormItem = {}
}) => {
  const { formilyTypeSource, setFormilyTypeSource, formilyTypes, remove } = useContext(
    FormilyContext
  );

  const options = formilyTypes.map((item) => {
    return {
      label: formilyConfig[item],
      value: item
    };
  });

  const handleTypeChange = (value: string, key: number) => {
    setFormilyTypeSource({
      ...formilyTypeSource,
      [key]: value
    });
  };

  return (
    <div className={styles.item}>
      <Title level={4} style={{ marginBottom: 0 }}>
        字段{arabicChinese.encode(field.name + 1)}
      </Title>

      <div className={styles.itemExtra}>
        <TextLink
          onClick={() => {
            remove?.(field.name);
          }}
        >
          删除字段
        </TextLink>
      </div>

      <Form.Item
        {...formLayout}
        label="类型"
        initialValue="inputs"
        name={[field.name, 'type']}
        fieldKey={[field.fieldKey, 'type']}
      >
        <Group
          options={options}
          onChange={(e: RadioChangeEvent) => {
            handleTypeChange(e.target.value, field.key);
          }}
        />
      </Form.Item>
      <Form.Item
        {...formLayout}
        label="名称"
        name={[field.name, 'name']}
        fieldKey={[field.fieldKey, 'name']}
        {...nameFormItem}
        rules={[{ required: true, message: '名称不能为空' }, ...(nameFormItem?.rules || [])]}
      >
        <Input style={{ width: 224 }} placeholder="输入信息名称" />
      </Form.Item>
      {['selects', 'multiSelects'].includes(formilyTypeSource[field.key]) && (
        <Options
          name={[field.name, 'options']}
          fieldKey={[field.fieldKey, 'options']}
          {...optionsFormItem}
        />
      )}
      <Form.Item
        {...formLayout}
        label="必填项"
        initialValue={false}
        style={{ marginBottom: 0 }}
        valuePropName="checked"
        name={[field.name, 'required']}
        fieldKey={[field.fieldKey, 'required']}
      >
        <Checkbox>是</Checkbox>
      </Form.Item>
    </div>
  );
};

export default FormilyItem;
