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

interface ResultItem {
  line: number
  lines: number[]
  desc: string
}

export default function ButtonModal() {
  const [searchParams] = useSearchParams()
  const [results, setResults] = useState<ResultItem[]>([])
  useEffect(() => {
    if (searchParams.get('results')) {
      setResults(JSON.parse(searchParams.get('results') || '') as ResultItem[])
      setOpen(true)
    }
  }, [searchParams])

  const { isLoading, post } = useAIStore()

  const handleAI = async () => {
    const message = await post({
      response_format: { type: 'json_object' },
      messages: [{ role: 'user', content: prompt.repeat }],
    })
    console.log(message.json)
    if (message.json && Array.isArray(message.json.results)) {
      setResults(message.json.results)
    }
  }

  const [open, setOpen] = useState(false)

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

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

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

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

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

  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.line}>{item.desc}</Checkbox>
                  </Col>
                ))}
              </Row>
            </Checkbox.Group>
          </Form.Item>
          {!results.length && <Empty></Empty>}
        </>
      ),
    },
    {
      title: '配置处理规则',
      content: (
        <>
          <Form.Item label="要处理的重复值数据">
            {checkedList.map((item, index) => (
              <p key={index}>
                {index + 1}、{results.find((resulst) => resulst.line === item)?.desc}
              </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={handleAI}>
                检查重复值字段
              </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>
    </>
  )
}
