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

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

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

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('fields', 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 { fieldOptions, getFieldName, getFieldNames } = 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 = {
    fields: searchParams.get('results')?.split(',') || [],
    action: '统一规则处理',
    rule: '不处理',
  }

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

  const { mutate, isPending, progress, message, remove } = useProcessData()
  // 开始处理
  const handleStart = () => {
    form.validateFields().then((values) => {
      const params = { ...values, fields: values.fields.join(','), rules: JSON.stringify(values.rules) }
      mutate(params)
    })
  }

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

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

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

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

          {action === '逐个配置规则处理' &&
            fields.map((field, index) => (
              <div key={field} style={{ marginBottom: 10 }}>
                <Form.Item label="字段" name={['rules', index, 'field']} initialValue={field}>
                  <span>{getFieldName(field)}</span>
                </Form.Item>
                <Form.Item label="缺失值字段处理规则" name={['rules', index, 'rule']}>
                  <Select options={ruleOptions} />
                </Form.Item>
                {rules[index]?.rule === '特殊值填充' && (
                  <Form.Item label="请填写特殊值" name={['rules', index, 'special']}>
                    <Input placeholder="请输入" />
                  </Form.Item>
                )}
                <Divider />
              </div>
            ))}
        </>
      ),
    },
    {
      title: '处理执行',
      content: (
        <>
          <p>缺失值处理字段：{getFieldNames(fields).join('、')}</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={handleSearch}>
                检查缺失值字段
              </Button>
            )}
            {current > 0 && <Button onClick={() => setCurrent(current - 1)}>上一步</Button>}
            {current < steps.length - 1 && (
              <Button type="primary" onClick={() => setCurrent(current + 1)} disabled={!fields.length}>
                下一步
              </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>
    </>
  )
}
