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'
import { useProcessData } from '../query'

interface ResultItem {
  name: string
  desc: string
}
export default function ButtonModal() {
  const [searchParams] = useSearchParams()
  const { fieldOptions, getFieldName } = useDataFieldQuery()
  const [results, setResults] = useState<ResultItem[]>([])
  const resultsOptions = results.map((result) => ({
    label: result.name,
    value: fieldOptions.find((option) => option.label === result.name)?.value || '',
  }))

  const selectOptions = resultsOptions.length ? resultsOptions : fieldOptions
  const { isLoading, post } = useAI({
    onComplete: (message) => {
      if (!message.content) return
      const parse = JSON.parse(message.content)
      console.log(parse)
      setResults(parse.results || [])
    },
  })

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

  const [open, setOpen] = useState(false)
  useEffect(() => {
    if (searchParams.get('results')) {
      setOpen(true)
    }
  }, [searchParams])
  const [current, setCurrent] = useState(0)
  const [form] = Form.useForm()
  const initialValues = {
    action: '取该字段平均值',
    field: searchParams.get('results') || '',
  }

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

  const ruleOptions = ['取该字段平均值', '删除逻辑错误值', '不处理']

  const { mutate, isPending, progress, message, remove } = useProcessData()
  // 开始处理
  const handleStart = () => {
    form.validateFields().then((values) => {
      mutate(values)
    })
  }

  // 关闭并重置
  const handleClose = () => {
    setOpen(false)
    setCurrent(0)
    remove()
    setResults([])
  }

  const steps = [
    {
      title: '请选择逻辑错误值字段',
      content: (
        <Form.Item name="field" rules={[{ required: true, message: '请选择逻辑错误值字段' }]}>
          <Radio.Group style={{ width: '100%' }}>
            <Row gutter={[10, 10]}>
              {selectOptions.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="逻辑错误值处理字段">{getFieldName(field)}</Form.Item>
          <Form.Item label="处理规则" name="action" rules={[{ required: true, message: '请选择处理规则' }]}>
            <Radio.Group options={ruleOptions} />
          </Form.Item>
        </>
      ),
    },
    {
      title: '处理执行',
      content: (
        <>
          <p>逻辑错误值处理字段：{getFieldName(field)}</p>
          <Flex vertical align="center" style={{ marginTop: '20px' }}>
            <Button type="primary" loading={isPending} onClick={handleStart}>
              开始处理
            </Button>
            <AppProgressSteps
              current={progress}
              items={[
                {
                  title: '检查字段处理规则',
                  description: message[1],
                },
                {
                  title: '逻辑错误值处理',
                  description: message[2],
                },
                {
                  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 === 0 && (
              <Button type="primary" loading={isLoading} onClick={handleAI}>
                检查逻辑错误值字段
              </Button>
            )}
            {current > 0 && <Button onClick={() => setCurrent(current - 1)}>上一步</Button>}
            {current < steps.length - 1 && (
              <Button type="primary" onClick={() => setCurrent(current + 1)} disabled={!field}>
                下一步
              </Button>
            )}
            {current === steps.length - 1 && (
              <Button type="primary" disabled={isPending} onClick={handleClose}>
                关闭
              </Button>
            )}
          </Flex>
        }
        destroyOnClose
        width={800}
        onCancel={handleClose}>
        <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>
    </>
  )
}
