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

export default function ButtonModal() {
  const { data = { list: [] } } = useDataQuery()
  const { fieldOptions, getFieldName } = useDataFieldQuery()
  // 数字类型字段
  const currentFieldOptions = fieldOptions.filter((item) => item.type.includes('VARCHAR'))

  const [open, setOpen] = useState(false)
  const [current, setCurrent] = useState(0)
  const [form] = Form.useForm()
  const [dataSource, setDataSource] = useState<{ key: number; label: string; value: string }[]>([])

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

  useEffect(() => {
    if (field && data.list?.length) {
      const uniqList = uniqBy(data.list, field)
      setDataSource(
        uniqList.map((item: any, index) => ({
          key: index + 1,
          label: item[field] || '',
          value: item[field] || '',
        }))
      )
    }
  }, [field, data.list])

  // 处理下一步按钮逻辑
  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.map((item: any) => {
          return {
            ...item,
            fields: item.fields.join(','),
          }
        })
      ),
    }
    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.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({ name: groupName, fields: [] }) // 添加新分组
                        setGroupName('')
                      }}>
                      添加分组
                    </Button>
                  </Flex>
                </Form.Item>

                {fields.map(({ key, name, ...restField }) => (
                  <Form.Item {...restField} label={rules[name]?.name} style={{ flex: 1 }} key={key}>
                    <Flex gap={10}>
                      <Form.Item name={[name, 'fields']} noStyle>
                        <Select options={dataSource} mode="multiple" style={{ width: '60%' }} />
                      </Form.Item>
                      <MinusCircleOutlined onClick={() => remove(name)} />
                    </Flex>
                  </Form.Item>
                ))}
              </>
            )}
          </Form.List>
        </>
      ),
    },
    {
      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}>
            {steps.map((item, index) => (
              <div key={index} hidden={current !== index} style={{ marginTop: '20px' }}>
                {item.content}
              </div>
            ))}
          </Form>
        </div>
      </Modal>
    </>
  )
}
