import { useState } from 'react'
import { Button, Flex, Modal, Radio, Input, Form, Row, Col, Checkbox } from 'antd'
import { useDataFieldQuery } from '@/hooks/useQuery'
import AppProgressSteps from '@/components/AppProgressSteps'
import { useProcessData } from '../query'
import { MinusCircleOutlined } from '@ant-design/icons'

export default function ButtonModal() {
  const { fieldOptions, getFieldName } = useDataFieldQuery()
  // 数字类型字段
  const currentFieldOptions = fieldOptions.filter(
    (item) => item.type.includes('DECIMAL') || item.type.includes('SMALLINT')
  )

  const [open, setOpen] = useState(false)
  const [current, setCurrent] = useState(0)
  const [form] = Form.useForm()

  const field = Form.useWatch('field', form)
  const action = Form.useWatch('action', form)
  const rules = Form.useWatch('rules', form) || []

  // 处理下一步按钮逻辑
  const handleNext = async () => {
    if (current === 0) {
      // 第一步验证表单
      await form.validateFields(['name', 'english_name', 'field'])
    } else if (current === 1) {
      await form.validateFields()
    }
    setCurrent(current + 1)
  }

  const { mutate, isPending, progress, message, remove } = useProcessData()

  // 开始处理
  const handleStart = () => {
    const values = form.getFieldsValue()
    const params = { ...values, rules: JSON.stringify(values.rules), action: '固定步长分箱' }
    mutate(params, {
      onSuccess: handleClose,
    })
  }

  // 关闭并重置
  const handleClose = () => {
    setOpen(false)
    setCurrent(0)
    remove()
  }
  const [groupName, setGroupName] = useState('')

  // 步骤定义
  const steps = [
    {
      title: '请选择数据分箱字段',
      content: (
        <>
          <Form.Item label="数据分箱字段名称" name="name" rules={[{ required: true, message: '请输入字段名称' }]}>
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item
            label="数据分箱字段英文名称"
            name="english_name"
            rules={[{ required: true, message: '请输入英文名称' }]}>
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item
            label="请选择数据分箱字段"
            name="field"
            rules={[{ required: true, message: '请选择数据分箱字段' }]}>
            <Radio.Group>
              <Row gutter={[10, 10]}>
                {currentFieldOptions.map((item) => (
                  <Col span={8} key={item.value}>
                    <Radio value={item.value}>{item.label}</Radio>
                  </Col>
                ))}
              </Row>
            </Radio.Group>
          </Form.Item>
        </>
      ),
    },
    {
      title: '配置数据分箱规则',
      content: (
        <>
          <Form.Item label="数据分箱操作字段">{getFieldName(field)}</Form.Item>
          <Form.Item name="action">
            <Radio.Group block options={['固定步长分箱', '自定义刻度值分箱']} optionType="button" buttonStyle="solid" />
          </Form.Item>
          {action === '固定步长分箱' && (
            <>
              <Form.Item label="最小值">
                <Form.Item name="min" rules={[{ required: true, message: '请输入最小值' }]} noStyle>
                  <Input placeholder="请输入" />
                </Form.Item>
                <p>分箱的取值规则为：大于等于最小值。例如最小值为5，则为&gt;=5</p>
              </Form.Item>
              <Form.Item label="最大值">
                <Form.Item name="max" rules={[{ required: true, message: '请输入最大值' }]} noStyle>
                  <Input placeholder="请输入" />
                </Form.Item>
                <p>分箱的取值规则为：小于等于最大值。例如最大值为200，则为&lt;=200</p>
              </Form.Item>
              <Form.Item label="步长值">
                <Form.Item name="step" rules={[{ required: true, message: '请输入步长值' }]} noStyle>
                  <Input placeholder="请输入" />
                </Form.Item>
                <p>以步长为分箱。例如步长值为100，则分箱结果为：5-100（含100），100-200（不含100）</p>
              </Form.Item>
              <Form.Item label="边界">
                <Form.Item name="include_min" noStyle valuePropName="checked">
                  <Checkbox>包含小于最小值</Checkbox>
                </Form.Item>
                <Form.Item name="include_max" noStyle valuePropName="checked">
                  <Checkbox>包含大于最大值</Checkbox>
                </Form.Item>
              </Form.Item>
            </>
          )}
          {action === '自定义刻度值分箱' && (
            <>
              <Form.List name="rules">
                {(fields, { add, remove }) => (
                  <>
                    <Form.Item label="数据分组名称">
                      <Flex gap={10} align="center">
                        <Input
                          placeholder="请输入"
                          value={groupName}
                          onChange={(e) => setGroupName(e.target.value)}
                          style={{ width: '60%' }}
                        />
                        <Button
                          type="primary"
                          onClick={() => {
                            if (!groupName) return
                            add(groupName) // 添加新分组
                            setGroupName('')
                          }}>
                          添加刻度
                        </Button>
                      </Flex>
                    </Form.Item>

                    {fields.map(({ key, name, ...restField }) => (
                      <Form.Item {...restField} label="刻度值" style={{ flex: 1 }} key={key}>
                        <Flex gap={10}>
                          <p style={{ width: '60%' }}>{rules[name]}</p>
                          <MinusCircleOutlined onClick={() => remove(name)} />
                        </Flex>
                      </Form.Item>
                    ))}
                  </>
                )}
              </Form.List>
              <Form.Item label="边界">
                <Form.Item name="include_min" noStyle valuePropName="checked">
                  <Checkbox>包含小于最小值</Checkbox>
                </Form.Item>
                <Form.Item name="include_max" noStyle valuePropName="checked">
                  <Checkbox>包含大于最大值</Checkbox>
                </Form.Item>
              </Form.Item>
            </>
          )}
        </>
      ),
    },
    {
      title: '处理执行',
      content: (
        <>
          <Flex vertical align="center" style={{ marginTop: '20px' }}>
            <Button type="primary" onClick={handleStart} loading={isPending}>
              开始处理
            </Button>
            <AppProgressSteps
              current={progress}
              items={[
                { title: '新建字段' },
                { title: '复制数据' },
                { title: '数据分箱处理' },
                { title: '处理结果', description: <>{message[3]}</> },
              ]}
            />
          </Flex>
        </>
      ),
    },
  ]

  return (
    <>
      <Button type="primary" onClick={() => setOpen(true)}>
        数据分箱
      </Button>
      <Modal
        title={steps[current]?.title}
        open={open}
        footer={
          <Flex justify="center" gap={20}>
            {current === 1 && <Button type="primary">AI智能建议</Button>}
            {current > 0 && <Button onClick={() => setCurrent(current - 1)}>上一步</Button>}
            {current < steps.length - 1 && (
              <Button type="primary" onClick={handleNext}>
                下一步
              </Button>
            )}
            {current === steps.length - 1 && (
              <Button type="primary" onClick={handleClose} disabled={isPending}>
                关闭
              </Button>
            )}
          </Flex>
        }
        destroyOnClose
        width={800}
        onCancel={handleClose}>
        <div style={{ minHeight: 300, padding: '20px 0' }}>
          <Form
            form={form}
            labelCol={{ span: 5 }}
            preserve={false}
            initialValues={{
              action: '固定步长分箱',
            }}>
            {steps.map((item, index) => (
              <div key={index} hidden={current !== index} style={{ marginTop: '20px' }}>
                {item.content}
              </div>
            ))}
          </Form>
        </div>
      </Modal>
    </>
  )
}
