import { useState } from 'react'
import { Button, Col, ColorPicker, Form, Modal, Row, Select } from 'antd'

function ColorField({ onChange, fieldOptions }: any) {
  const [modalVisible, setModalVisible] = useState(false)
  const [modalForm] = Form.useForm()

  const handleModalOk = () => {
    modalForm.validateFields().then((values) => {
      onChange?.(values.fieldColors)
      setModalVisible(false)
    })
  }
  return (
    <>
      <Button type="dashed" onClick={() => setModalVisible(true)}>
        自定义颜色字段
      </Button>

      <Modal
        title="自定义颜色字段"
        open={modalVisible}
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
        width={400}>
        <Form form={modalForm} layout="vertical">
          <Form.List name="fieldColors">
            {(fields, { add, remove }) => (
              <>
                {fields.map((field) => (
                  <Row gutter={20} key={field.key} align="top">
                    <Col span={14}>
                      <Form.Item
                        {...field}
                        name={[field.name, 'field']}
                        rules={[{ required: true, message: '请选择字段' }]}>
                        <Select options={fieldOptions} placeholder="请选择字段" />
                      </Form.Item>
                    </Col>
                    <Col span={4}>
                      <Form.Item
                        {...field}
                        name={[field.name, 'color']}
                        getValueFromEvent={(event) => event.toHexString()}
                        rules={[{ required: true, message: '请选择颜色' }]}>
                        <ColorPicker />
                      </Form.Item>
                    </Col>
                    <Col span={6}>
                      <Button type="dashed" onClick={() => remove(field.name)}>
                        删除
                      </Button>
                    </Col>
                  </Row>
                ))}
                <Form.Item>
                  <Button type="dashed" onClick={() => add()} block>
                    添加字段颜色
                  </Button>
                </Form.Item>
              </>
            )}
          </Form.List>
        </Form>
      </Modal>
    </>
  )
}

export default ColorField
