import { useState } from 'react'
import { Button, Flex, Modal, Select } from 'antd'
import { useDataFieldQuery } from '@/hooks/useQuery'

export default function SelectFieldButtonModal({
  fieldType,
  onChange,
}: {
  fieldType: string
  onChange?: (value: string) => void
}) {
  const [open, setOpen] = useState(false)
  const { fieldOptions } = useDataFieldQuery()
  const [value, setValue] = useState<string>('')

  const currentFieldOptions = fieldOptions.filter((option) => {
    if (fieldType === 'string') return option.type.includes('VARCHAR')
    if (fieldType === 'number') return option.type.includes('DECIMAL') || option.type.includes('SMALLINT')
    return true
  })

  const handleOk = () => {
    setOpen(false)
    if (value && onChange) onChange(value)
    setValue('')
  }

  const Footer = () => {
    return (
      <Flex justify="center">
        <Button type="primary" onClick={handleOk}>
          确定
        </Button>
      </Flex>
    )
  }

  return (
    <>
      <Button type="primary" onClick={() => setOpen(true)}>
        添加字段
      </Button>
      <Modal title="添加字段" width={400} open={open} footer={<Footer />} onCancel={() => setOpen(false)}>
        <div style={{ padding: '20px 0' }}>
          <Select
            placeholder="请选择字段"
            options={currentFieldOptions}
            value={value}
            allowClear
            onChange={setValue}
            style={{ width: '100%' }}></Select>
        </div>
      </Modal>
    </>
  )
}
