import { useState } from 'react'
import { Button, Radio, Flex, Modal, Empty } from 'antd'
import type { RadioChangeEvent } from 'antd'
import { useNavigate } from 'react-router'
import AppSteps from '@/components/AppSteps'
import { useAI } from '@/hooks/useAI'
import prompt from '@/utils/prompt'

interface ResultItem {
  name: string
  desc: string
}

export default function ButtonModal() {
  const [results, setResults] = useState<ResultItem[]>([])
  const resultsOptions = results.map((result) => result.name)

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

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

  const [value, setValue] = useState(1)

  const onChange = (e: RadioChangeEvent) => {
    setValue(e.target.value)
  }
  const next = () => {
    setCurrent(current + 1)
  }

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

  const steps = [{ title: '探索逻辑错误字段' }, { title: '处理逻辑错误' }]

  const style: React.CSSProperties = {
    display: 'flex',
    flexDirection: 'column',
    gap: 8,
  }
  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={!!value}>
                下一步
              </Button>
            )}
            {current === steps.length - 1 && (
              <Button
                type="primary"
                onClick={() => navigate({ pathname: '/data/preprocess/error', search: `?results=${value}` })}>
                跳转数据预处理
              </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>
          <Radio.Group options={resultsOptions} value={value} onChange={onChange} style={style} />
          {!results.length && <Empty></Empty>}
        </div>
      </Modal>
    </>
  )
}
