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

export default function ButtonModal() {
  const [searchParams] = useSearchParams()
  const [results, setResults] = useState<Array<{ lines: number[]; desc: string }>>([
    { lines: [1, 3], desc: '第1行、第3行的数据完全一样' },
    { lines: [2, 8], desc: '第2行、第8行的数据完全一样' },
  ])
  useEffect(() => {
    if (searchParams.get('results')) {
      setResults(JSON.parse(searchParams.get('results') || '') as any)
      setOpen(true)
    }
  }, [searchParams])

  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.repeat }] })
  }

  const [open, setOpen] = useState(false)

  const [current, setCurrent] = useState(0)
  const [form] = Form.useForm()
  const initialValues = {
    action: '保留1条，删除剩余重复数据',
  }

  const checkedList: string[] = Form.useWatch('checkedList', form) || []

  const ruleOptions = ['保留1条，删除剩余重复数据', '全部删除', '不处理']

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

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

  const steps = [
    {
      title: '请选择重复值数据',
      content: (
        <Form.Item name="checkedList">
          <Checkbox.Group>
            <Row gutter={[10, 10]}>
              {results.map((item, index) => (
                <Col span={24} key={index}>
                  <Checkbox value={item.desc}>{item.desc}</Checkbox>
                </Col>
              ))}
            </Row>
          </Checkbox.Group>
          {!results.length && <Empty></Empty>}
        </Form.Item>
      ),
    },
    {
      title: '配置处理规则',
      content: (
        <>
          <Form.Item label="要处理的重复值数据">
            {checkedList.map((item, index) => (
              <p key={index}>
                {index + 1}、{item}
              </p>
            ))}
          </Form.Item>
          <Form.Item label="处理规则" name="action">
            <Radio.Group options={ruleOptions} />
          </Form.Item>
        </>
      ),
    },
    {
      title: '处理执行',
      content: (
        <>
          <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={!checkedList.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>
    </>
  )
}
