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

const CheckboxGroup = Checkbox.Group

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

  const navigate = useNavigate()

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

  const [checkedList, setCheckedList] = useState<string[]>([])

  const checkAll = resultsOptions.length === checkedList.length
  const indeterminate = checkedList.length > 0 && checkedList.length < resultsOptions.length

  const onChange = (list: string[]) => {
    setCheckedList(list)
  }

  const onCheckAllChange: CheckboxProps['onChange'] = (e) => {
    setCheckedList(e.target.checked ? resultsOptions : [])
  }

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

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

  const steps = [
    {
      title: '探索缺失值字段',
      content: (
        <>
          <Flex justify="space-between" style={{ marginBottom: 20 }}>
            探索结果：
            <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>
              全选
            </Checkbox>
          </Flex>
          <CheckboxGroup options={resultsOptions} value={checkedList} onChange={onChange} />
          {!results.length && <Empty></Empty>}
        </>
      ),
    },
    {
      title: '探索字段缺失值',
      content: (
        <>
          <Flex justify="space-between" style={{ marginBottom: 20 }}>
            探索结果：
          </Flex>
          {results.map((item) => (
            <p key={item.name}>
              {item.name}: 该字段有缺失值的数据有：{item.desc}
            </p>
          ))}
        </>
      ),
    },
    {
      title: '填充字段缺失值',
      content: (
        <>
          <Flex justify="space-between" style={{ marginBottom: 20 }}>
            请选择需要填充的字段：
            <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>
              全选
            </Checkbox>
          </Flex>
          <CheckboxGroup options={resultsOptions} value={checkedList} onChange={onChange} />
        </>
      ),
    },
  ]

  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 type="primary" disabled={!checkedList.length} onClick={() => next()}>
                进一步探索字段缺失值情况
              </Button>
            )}

            {current > 0 && <Button onClick={() => prev()}>上一步</Button>}
            {current > 0 && current < steps.length - 1 && (
              <Button type="primary" onClick={() => next()}>
                下一步
              </Button>
            )}
            {current === steps.length - 1 && (
              <Button
                type="primary"
                disabled={!checkedList.length}
                onClick={() =>
                  navigate({ pathname: '/data/preprocess/null', search: `?results=${checkedList.join(',')}` })
                }>
                跳转数据预处理
              </Button>
            )}
          </Flex>
        }
        destroyOnClose
        width={800}
        onCancel={() => setOpen(false)}>
        <div style={{ minHeight: 300, padding: '40px 0' }}>
          <AppSteps current={current} items={steps} style={{ marginBottom: 40 }} />
          <div>{steps[current].content}</div>
        </div>
      </Modal>
    </>
  )
}
