import React, { useState } from 'react';
import { Form, Input, Button, Space, Select, Col } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { get, post } from '../../services';

const methods = [
  { label: 'get', value: 'get' },
  { label: 'post', value: 'post' },
];

const RequestTest = () => {
  const [protocal, setprotocal] = useState('http://');
  const [form] = Form.useForm();

  const onFinish = values => {
    const url = protocal + values.url;
    const methodMap = { get, post };
    const { method } = values;
    const params =
      values.params &&
      values.params.reduce((param, { key, value }) => {
        // eslint-disable-next-line no-param-reassign
        param[key.trim()] = value.trim();
        return param;
      }, {});
    if (window.location.host === values.url) {
      methodMap[method](url, params).catch(err => {
        // eslint-disable-next-line no-console
        console.error(err);
      });
    } else {
      const proxyUrl = url.replace(
        // eslint-disable-next-line no-useless-escape
        /^https?:\/\/([^\/]+)/,
        () => `${window.location.origin}`,
      );
      methodMap[method](proxyUrl, params).catch(err => {
        // eslint-disable-next-line no-console
        console.error(err);
      });
    }
  };

  const handleProtoSelectChange = v => {
    setprotocal(v);
  };

  const protocalBefore = (
    <Select
      defaultValue="http://"
      className="select-before"
      onChange={handleProtoSelectChange}
    >
      <Select.Option value="http://">http://</Select.Option>
      <Select.Option value="https://">https://</Select.Option>
    </Select>
  );

  const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
  };

  const paramItemLayout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 24 },
  };

  return (
    <Form
      form={form}
      name="dynamic_form_nest_item"
      onFinish={onFinish}
      {...formItemLayout}
      autoComplete="off"
    >
      <Form.Item
        name="url"
        label="url"
        rules={[{ required: true, message: 'Missing url' }]}
        initialValue={window.location.host}
      >
        <Input addonBefore={protocalBefore} />
      </Form.Item>
      <Form.Item
        name="method"
        label="method"
        rules={[{ required: true, message: 'Missing method' }]}
        initialValue="get"
      >
        <Select options={methods} />
      </Form.Item>
      <Form.List name="params">
        {(fields, { add, remove }) => (
          <>
            {fields.map(field => (
              <Col span={14} offset={5} key={field.key}>
                <Space align="start">
                  <Form.Item
                    {...field}
                    label="key"
                    name={[field.name, 'key']}
                    fieldKey={[field.fieldKey, 'key']}
                    {...paramItemLayout}
                    rules={[{ required: true, message: 'Missing key' }]}
                  >
                    <Input />
                  </Form.Item>
                  <Form.Item
                    {...field}
                    label="value"
                    {...paramItemLayout}
                    fieldKey={[field.fieldKey, 'value']}
                    name={[field.name, 'value']}
                  >
                    <Input />
                  </Form.Item>
                  <MinusCircleOutlined onClick={() => remove(field.name)} />
                </Space>
              </Col>
            ))}
            <Form.Item
              wrapperCol={{
                span: 14,
                offset: 5,
              }}
            >
              <Button
                type="dashed"
                onClick={() => {
                  add();
                }}
                block
              >
                <PlusOutlined /> Add params
              </Button>
            </Form.Item>
          </>
        )}
      </Form.List>

      <Form.Item wrapperCol={{ span: 5, offset: 10 }}>
        <Button type="primary" htmlType="submit" block>
          Submit
        </Button>
      </Form.Item>
    </Form>
  );
};

export default RequestTest;
