import { Alert, DatePicker, Form, FormInstance, Input } from 'antd'
import TextArea from 'antd/lib/input/TextArea'
import moment from 'moment'
import { useParams } from 'react-router-dom'
import TOML from 'toml'

import { cloudConfigControllerListParameterAttributes } from 'apiClient/services/devops'
import { CloudconfigClusterType } from 'apiClient/services/devops/interface'

import { flattenObject, typeCheck } from '../CurrentConfig/Current'

import { fixedFiles } from './EditParamForm'

export type BatchModifyFormType = {
  component: string
  toml: string
}

export default function BatchModifyForm({
  clusterType,
  form,
  component,
  version
}: {
  clusterType?: CloudconfigClusterType
  form: FormInstance
  component?: string
  version?: string
}) {
  form.setFieldsValue({ component: component })
  form.setFieldsValue({ expire_at: moment().add(2, 'hours') })
  return (
    <>
      <Form.Item label="Note">
        <Alert
          message="all parameters in toml will be set as custom parameters locally."
          type="warning"
        />
      </Form.Item>
      <Form.Item label="Component" name="component">
        <Input
          disabled={true}
          style={{ color: 'black' }}
          bordered={false}
        ></Input>
      </Form.Item>
      <Form.Item
        label="Toml File"
        name="toml"
        required={true}
        rules={[
          { required: true },
          {
            validator: async (_: any, value: string) => {
              try {
                const parsed = TOML.parse(value)
                const flat = flattenObject(parsed)
                const dict =
                  (
                    await cloudConfigControllerListParameterAttributes(
                      component!,
                      version!,
                      {
                        cluster_type: clusterType || 'DEDICATED_TIDB'
                      }
                    )
                  ).data.items || []

                for (const [key, val] of Object.entries(flat)) {
                  const found = dict.find((item: any) => item.name === key)
                  if (
                    !found &&
                    fixedFiles.includes(component!) &&
                    clusterType === 'DEDICATED_TIDB'
                  ) {
                    return Promise.reject(
                      new Error(key + ' does not exist in param dict ')
                    )
                  }
                  if (found) {
                    const tc = typeCheck(val, found?.type || 'string')
                    if (!tc) {
                      return Promise.reject(
                        new Error(
                          found?.name! +
                            "'s type is not consistent with param dict " +
                            found?.type
                        )
                      )
                    }
                  }
                }
                return Promise.resolve()
              } catch (e) {
                return Promise.reject(
                  new Error('fail to read toml: ' + String(e))
                )
              }
            }
          }
        ]}
      >
        <TextArea rows={10}></TextArea>
      </Form.Item>
    </>
  )
}
