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 { useAIStore } from '@/ai/useAIStore'
import prompt from '@/ai/prompt'
import { useDataFieldQuery } from '@/hooks/useQuery'

interface ResultItem {
  name: string
  desc: string
}

export default function ButtonModal() {
  const { fieldOptions } = useDataFieldQuery()

  const [results, setResults] = useState<ResultItem[]>([])
  const resultsOptions = results.map((result) => ({
    label: result.name,
    value: fieldOptions.find((option) => option.label === result.name)?.value || '',
  }))

  const isLoading = useAIStore((state) => state.isLoading)
  const post = useAIStore((state) => state.post)

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

  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={handleAI}>
                智能探索字段数据逻辑错误
              </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>
    </>
  )
}
