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'

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 = {
    rule: '1',
  }

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

  const ruleOptions = [
    { label: '保留1条，删除剩余重复数据', value: '1' },
    { label: '全部删除', value: '2' },
    { label: '不处理', value: '3' },
  ]

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

  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="rule">
            <Radio.Group options={ruleOptions} />
          </Form.Item>
        </>
      ),
    },
    {
      title: '处理执行',
      content: (
        <>
          <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>
    </>
  )
}
