import KFIcon from '@/components/KFIcon';
import { getParamComponent, getParamRules } from '@/pages/Experiment/components/AddExperimentModal';
import { type PipelineGlobalParam } from '@/types';
import { to } from '@/utils/promise';
import { modalConfirm } from '@/utils/ui';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Drawer, Form, Input, Radio, Tooltip } from 'antd';
import { NamePath } from 'antd/es/form/interface';
import { forwardRef, useImperativeHandle } from 'react';
import styles from './index.less';

type GlobalParamsDrawerProps = {
  open: boolean;
  onClose: () => void;
  globalParam: PipelineGlobalParam[] | null;
};

const GlobalParamsDrawer = forwardRef(
  ({ open = false, onClose, globalParam = [] }: GlobalParamsDrawerProps, ref) => {
    const [form] = Form.useForm();

    useImperativeHandle(
      ref,
      () => ({
        validateFields: async () => {
          const [values, error] = await to(form.validateFields());
          if (!error && values) {
            return values;
          } else {
            return Promise.reject(error);
          }
        },
        getFieldsValue: () => {
          return form.getFieldsValue();
        },
      }),
      [form],
    );

    // 处理参数类型变化
    const handleTypeChange = (name: NamePath) => {
      form.setFieldValue(name, null);
    };

    const removeParameter = (name: number, remove: (param: number) => void) => {
      modalConfirm({
        title: '删除后，该全局参数将不可恢复',
        content: '是否确认删除?',
        onOk: () => {
          remove(name);
        },
      });
    };

    return (
      <Drawer
        rootStyle={{ marginTop: '55px' }}
        title="全局参数"
        placement="right"
        closeIcon={false}
        getContainer={false}
        onClose={onClose}
        open={open}
        width={520}
      >
        <Form
          name="global_params_form"
          autoComplete="off"
          form={form}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 19 }}
          initialValues={{ global_param: globalParam }}
          labelAlign="left"
        >
          <Form.List name="global_param">
            {(fields, { add, remove }) => (
              <>
                {fields.map(({ key, name, ...restField }) => (
                  <div key={key} className={styles['form-item']}>
                    <Form.Item
                      {...restField}
                      name={[name, 'param_name']}
                      label="参数名称"
                      validateTrigger={[]}
                      rules={[
                        { required: true, message: '请输入参数名称' },
                        {
                          validator: (_, value) => {
                            const list = form.getFieldValue('global_param') || [];
                            const names = list.filter((item: any) => item?.param_name === value);
                            if (value && names.length > 1) {
                              return Promise.reject('参数名称不能重复');
                            } else {
                              return Promise.resolve();
                            }
                          },
                        },
                      ]}
                    >
                      <Input
                        placeholder="请输入参数名称"
                        allowClear
                        onBlur={() => form.validateFields()}
                      />
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      name={[name, 'description']}
                      label="参数描述"
                      rules={[{ required: true, message: '请输入参数描述' }]}
                    >
                      <Input.TextArea
                        placeholder="请输入参数描述"
                        autoSize={{ minRows: 2, maxRows: 4 }}
                        allowClear
                      />
                    </Form.Item>
                    <Form.Item
                      {...restField}
                      name={[name, 'param_type']}
                      label="类　　型"
                      rules={[{ required: true, message: '请选择类型' }]}
                    >
                      <Radio.Group
                        onChange={() => handleTypeChange(['global_param', name, 'param_value'])}
                      >
                        <Radio value={1}>字符串</Radio>
                        <Radio value={2}>整型</Radio>
                        <Radio value={3}>布尔类型</Radio>
                      </Radio.Group>
                    </Form.Item>
                    <Form.Item
                      noStyle
                      shouldUpdate={(prev, cur) =>
                        prev.global_param?.[name]?.param_type !==
                        cur.global_param?.[name]?.param_type
                      }
                    >
                      {({ getFieldValue }) => {
                        const type = getFieldValue(['global_param', name, 'param_type']);
                        return (
                          <>
                            <Form.Item
                              {...restField}
                              name={[name, 'param_value']}
                              label="值"
                              rules={getParamRules(type, true)}
                            >
                              {getParamComponent(type)}
                            </Form.Item>
                            {/* {type !== 3 && (
                              <Form.Item
                                {...restField}
                                name={[name, 'is_sensitive']}
                                label="脱敏显示"
                                rules={[{ required: true, message: '请选择' }]}
                                tooltip="展示关联的流水线的参数，脱敏的参数以xxxx展示"
                              >
                                <Radio.Group>
                                  <Radio value={1}>是</Radio>
                                  <Radio value={0}>否</Radio>
                                </Radio.Group>
                              </Form.Item>
                            )} */}
                          </>
                        );
                      }}
                    </Form.Item>
                    <Tooltip title="删除参数">
                      <Button
                        className={styles['form-item__delete-button']}
                        type="link"
                        onClick={() => removeParameter(name, remove)}
                        icon={<KFIcon type="icon-shanchu" />}
                      ></Button>
                    </Tooltip>
                  </div>
                ))}
                <Form.Item className={styles['form-item-add']}>
                  <Button
                    className={styles['form-item-add__add-button']}
                    type="link"
                    onClick={() => add()}
                    icon={<PlusOutlined />}
                  >
                    流水线参数
                  </Button>
                </Form.Item>
              </>
            )}
          </Form.List>
        </Form>
      </Drawer>
    );
  },
);

export default GlobalParamsDrawer;
