import { useEffect, useState } from 'react'
import { Button, Flex, Modal, Radio, Form, Row, Col } from 'antd'
import { useDataFieldQuery } from '@/hooks/useQuery'
import AppProgressSteps from '@/components/AppProgressSteps'
import { useSearchParams } from 'react-router'
import { useAI } from '@/hooks/useAI'
import prompt from '@/utils/prompt'

export default function ButtonModal() {
  const [searchParams] = useSearchParams()

  const { isLoading, post } = useAI({
    onComplete: (message) => {
      try {
        const parse = JSON.parse(message.content)
        console.log(parse)
      } catch (error) {
        console.error(error)
      }
    },
  })

  const handleSearch = () => {
    post({
      response_format: { type: 'json_object' },
      messages: [{ role: 'user', content: prompt.max }],
    })
  }

  const { fieldOptions } = useDataFieldQuery()

  const [open, setOpen] = useState(false)
  useEffect(() => {
    if (searchParams.get('results')) {
      setOpen(true)
    }
  }, [searchParams])
  const [current, setCurrent] = useState(0)
  const [form] = Form.useForm()
  const initialValues = {
    checked: '',
    rule: '1',
  }

  const checked = Form.useWatch('checked', form)

  const ruleOptions = [
    { label: '取该字段平均值', value: '1' },
    { label: '删除过小值', value: '2' },
    { label: '不处理', value: '3' },
  ]

  const [step, setStep] = useState<number>(-1)

  const steps = [
    {
      title: '请选择过小值字段',
      content: (
        <Form.Item name="checked" rules={[{ required: true, message: '请选择过小值字段' }]}>
          <Radio.Group>
            <Row gutter={[10, 10]}>
              {fieldOptions.map((item) => (
                <Col span={6} key={item.value}>
                  <Radio value={item.value}>{item.label}</Radio>
                </Col>
              ))}
            </Row>
          </Radio.Group>
        </Form.Item>
      ),
    },
    {
      title: '配置处理规则',
      content: (
        <>
          <Form.Item label="过小值处理字段">{checked}</Form.Item>
          <Form.Item label="处理规则" name="rule" rules={[{ required: true, message: '请选择处理规则' }]}>
            <Radio.Group options={ruleOptions} />
          </Form.Item>
        </>
      ),
    },
    {
      title: '处理执行',
      content: (
        <>
          <p>过小值处理字段：{checked}</p>
          <Flex vertical align="center" style={{ marginTop: '20px' }}>
            <Button type="primary" onClick={() => setStep(1)}>
              开始处理
            </Button>
            <AppProgressSteps
              current={step}
              items={[
                {
                  title: <>检查字段处理规则</>,
                },
                {
                  title: <>过小值处理</>,
                },
                {
                  title: <>处理结果</>,
                  description: (
                    <>
                      累计处理XX个字段
                      <br />
                      累计处理XX条记录
                    </>
                  ),
                },
              ]}
            />
          </Flex>
        </>
      ),
    },
  ]

  return (
    <>
      <Button type="primary" onClick={() => setOpen(true)}>
        处理过小值
      </Button>
      <Modal
        title={steps[current].title}
        open={open}
        footer={
          <Flex justify="center" gap={20}>
            {current === 0 && (
              <Button type="primary" loading={isLoading} onClick={handleSearch}>
                检查过小值字段
              </Button>
            )}
            {current > 0 && <Button onClick={() => setCurrent(current - 1)}>上一步</Button>}
            {current < steps.length - 1 && (
              <Button type="primary" onClick={() => setCurrent(current + 1)} disabled={!checked}>
                下一步
              </Button>
            )}
            {current === steps.length - 1 && (
              <Button type="primary" onClick={() => setOpen(false)}>
                关闭
              </Button>
            )}
          </Flex>
        }
        destroyOnClose
        width={800}
        onCancel={() => setOpen(false)}>
        <div style={{ minHeight: 300, padding: '20px 0' }}>
          <Form form={form} labelCol={{ span: 5 }} preserve={false} initialValues={initialValues}>
            {steps.map((item, index) => (
              <div key={index} hidden={current !== index} style={{ marginTop: '20px' }}>
                {item.content}
              </div>
            ))}
          </Form>
        </div>
      </Modal>
    </>
  )
}
