import { useState } from 'react'
import { Button, Empty, Flex, Modal } from 'antd'
import { useNavigate } from 'react-router'
import AppSteps from '@/components/AppSteps'

import { useAI } from '@/hooks/useAI'
import prompt from '@/utils/prompt'

export default function ButtonModal() {
  const [results, setResults] = useState<Array<{ lines: number[]; desc: string }>>([
    { lines: [1, 3], desc: '第1行、第3行的数据完全一样' },
    { lines: [2, 8], desc: '第2行、第8行的数据完全一样' },
  ])

  const { isLoading, post } = useAI({
    onComplete: (message) => {
      if (!message.content) return
      const parse = JSON.parse(message.content)
      console.log(parse)
      setResults(parse.results || [])
    },
  })
  const handleSearch = () => {
    post({
      response_format: { type: 'json_object' },
      messages: [{ role: 'user', content: prompt.repeat }],
    })
  }

  const navigate = useNavigate()
  const [open, setOpen] = useState(false)
  const [current, setCurrent] = useState(0)

  const next = () => {
    setCurrent(current + 1)
  }

  const prev = () => {
    setCurrent(current - 1)
  }

  const steps = [{ title: '探索重复值' }, { title: '处理重复值' }]

  return (
    <>
      <Button type="primary" onClick={() => setOpen(true)}>
        重复值
      </Button>
      <Modal
        title="重复值探索"
        open={open}
        footer={
          <Flex justify="center" gap={20}>
            {current === 0 && (
              <Button type="primary" loading={isLoading} onClick={handleSearch}>
                智能探索重复值字段
              </Button>
            )}
            {current > 0 && <Button onClick={() => prev()}>上一步</Button>}
            {current < steps.length - 1 && (
              <Button type="primary" onClick={() => next()} disabled={!results.length}>
                下一步
              </Button>
            )}
            {current === steps.length - 1 && (
              <Button
                type="primary"
                onClick={() =>
                  navigate({ pathname: '/data/preprocess/repeat', search: `?results=${JSON.stringify(results)}` })
                }>
                跳转数据预处理
              </Button>
            )}
          </Flex>
        }
        destroyOnClose
        width={800}
        onCancel={() => setOpen(false)}>
        <div style={{ minHeight: 300, padding: '40px 0' }}>
          <AppSteps current={current} items={steps} style={{ marginBottom: 40 }} />
          <Flex justify="space-between" style={{ marginBottom: 20 }}>
            探索结果：
          </Flex>
          {results.map((item, index) => (
            <p key={index}>
              {index + 1}、 {item.desc}
            </p>
          ))}
          {!results.length && <Empty></Empty>}
        </div>
      </Modal>
    </>
  )
}
