import { useEffect, useState } from 'react'
import { Button, Checkbox, Flex, Modal, Radio, Select, Input, Form, Row, Col, Divider } 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)
        if (parse.results.length) form.setFieldValue('checkedList', parse.results.map((item: any) => item.name) || [])
      } catch (error) {
        console.error(error)
      }
    },
  })

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

  const { data: fields = [] } = 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 = {
    checkedList: searchParams.get('results')?.split(',') || [],
    method: 'unified',
    rule: '1',
  }

  const checkedList: string[] = Form.useWatch('checkedList', form) || []
  const method = Form.useWatch('method', form)
  const rule = Form.useWatch('rule', form)
  const rules = Form.useWatch('rules', form) || {}

  const methodOptions = [
    { label: '统一规则处理', value: 'unified' },
    { label: '逐个配置规则处理', value: 'individual' },
  ]

  const ruleOptions = [
    { label: '不处理', value: '1' },
    { label: 'AI智能填充', value: '2' },
    { label: '删除', value: '3' },
    { label: '平均值填充', value: '4' },
    { label: '特殊值填充', value: '5' },
    { label: '热卡填充（上）', value: '6' },
    { label: '热卡填充（下）', value: '7' },
  ]

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

  const steps = [
    {
      title: '请选择缺失值字段',
      content: (
        <Form.Item name="checkedList">
          <Checkbox.Group>
            <Row gutter={[10, 10]}>
              {fields.map((item) => (
                <Col span={6} key={item.english_name}>
                  <Checkbox value={item.name}>{item.name}</Checkbox>
                </Col>
              ))}
            </Row>
          </Checkbox.Group>
        </Form.Item>
      ),
    },
    {
      title: '配置处理规则',
      content: (
        <>
          <Form.Item label="缺失值字段处理方法" name="method">
            <Radio.Group options={methodOptions} />
          </Form.Item>

          {/* 统一规则处理 */}
          {method === 'unified' && (
            <>
              <Form.Item label="缺失值字段处理规则" name="rule">
                <Select options={ruleOptions} />
              </Form.Item>

              {rule === '5' && (
                <Form.Item label="请填写特殊值" name="special">
                  <Input placeholder="请输入" />
                </Form.Item>
              )}
            </>
          )}

          {/* 逐个配置规则处理 */}
          {method === 'individual' &&
            checkedList.map((field) => (
              <div key={field} style={{ marginBottom: 10 }}>
                <Form.Item label="字段">{field}</Form.Item>
                <Form.Item label="缺失值字段处理规则" name={['rules', field, 'rule']}>
                  <Select options={ruleOptions} />
                </Form.Item>
                {rules[field]?.rule === '5' && (
                  <Form.Item label="请填写特殊值" name={['rules', field, 'special']}>
                    <Input placeholder="请输入" />
                  </Form.Item>
                )}
                <Divider />
              </div>
            ))}
        </>
      ),
    },
    {
      title: '处理执行',
      content: (
        <>
          <p>缺失值处理字段：{checkedList.join(', ')}</p>
          <Flex vertical align="center" style={{ marginTop: '20px' }}>
            <Button type="primary" onClick={() => setStep(1)}>
              开始处理
            </Button>
            <AppProgressSteps
              style={{ margin: '80px' }}
              current={step}
              items={[
                {
                  title: (
                    <>
                      第一步
                      <br />
                      检查字段处理规则
                    </>
                  ),
                },
                {
                  title: (
                    <>
                      第二步
                      <br />
                      缺失值处理
                    </>
                  ),
                },
                {
                  title: (
                    <>
                      第三步
                      <br />
                      处理结果
                    </>
                  ),
                  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={!checkedList.length}>
                下一步
              </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>
    </>
  )
}
