import { useState } from 'react'
import { Button, Flex, Modal, Radio, Input, Form, Select } from 'antd'
import { useDataFieldQuery } from '@/hooks/useQuery'
import AppProgressSteps from '@/components/AppProgressSteps'
import { useProcessData } from '../query'

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

  const [open, setOpen] = useState(false)
  const [current, setCurrent] = useState(0)
  const [form] = Form.useForm()
  const [fields, setFields] = useState<{ field: string; order: number }[]>([])

  const { mutate, isPending, progress, message, remove } = useProcessData()
  // 开始处理
  const handleStart = () => {
    form.validateFields().then((values) => {
      mutate({ ...values, fields: JSON.stringify(fields) })
    })
  }

  // 关闭并重置
  const handleClose = () => {
    setOpen(false)
    setCurrent(0)
    remove()
  }

  // 下一步
  const handleNext = async () => {
    await form.validateFields()
    setCurrent(current + 1)
  }

  // Add concatenation field
  const addField = () => {
    const newField = form.getFieldValue('fieldToAdd')
    if (!newField) {
      message.warning('请选择要添加的字段')
      return
    }

    const updatedFields = [
      ...fields,
      {
        field: newField,
        order: fields.length,
      },
    ]

    setFields(updatedFields)
    form.setFieldsValue({ fieldToAdd: undefined })
  }

  // Move field up in order
  const moveFieldUp = (index: number) => {
    if (index <= 0) return
    const newFields = [...fields]
    const temp = newFields[index]
    newFields[index] = newFields[index - 1]
    newFields[index - 1] = temp

    // Update order property
    newFields.forEach((field, idx) => {
      field.order = idx
    })

    setFields(newFields)
  }

  // Move field down in order
  const moveFieldDown = (index: number) => {
    if (index >= fields.length - 1) return
    const newFields = [...fields]
    const temp = newFields[index]
    newFields[index] = newFields[index + 1]
    newFields[index + 1] = temp

    // Update order property
    newFields.forEach((field, idx) => {
      field.order = idx
    })

    setFields(newFields)
  }

  // Remove field from list
  const removeField = (index: number) => {
    const newFields = fields.filter((_, idx) => idx !== index)

    // Update order property
    newFields.forEach((field, idx) => {
      field.order = idx
    })

    setFields(newFields)
  }

  // Steps definition
  const steps = [
    {
      title: '请选择拼接字段',
      content: (
        <>
          <Form.Item label="拼接新字段名称" name="name" rules={[{ required: true, message: '请输入字段名称' }]}>
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item
            label="拼接新字段英文名称"
            name="english_name"
            rules={[{ required: true, message: '请输入英文名称' }]}>
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item
            label="拼接新字段类型"
            name="fieldType"
            rules={[{ required: true, message: '请选择拼接新字段类型' }]}
            initialValue="string">
            <Radio.Group options={[{ label: '文本', value: 'string' }]} />
          </Form.Item>
          <Form.Item
            label="请选择数据拼接字段"
            name="fields"
            rules={[
              {
                required: true,
                message: '请添加至少一个拼接字段',
                validator: () => (fields.length > 0 ? Promise.resolve() : Promise.reject('请添加至少一个拼接字段')),
              },
            ]}>
            <div>
              <Flex gap={10}>
                <Form.Item name="fieldToAdd" noStyle>
                  <Select placeholder="选择要添加的字段" options={fieldOptions} />
                </Form.Item>
                <Button type="primary" onClick={addField}>
                  添加拼接字段
                </Button>
              </Flex>

              {fields.map((item, index) => {
                const fieldInfo = fieldOptions.find((f) => f.value === item.field)
                return (
                  <Flex key={index} gap={10} style={{ marginTop: '10px' }}>
                    <div style={{ flex: 1, border: '1px solid #d9d9d9', padding: '4px 11px', borderRadius: '6px' }}>
                      {fieldInfo ? `${fieldInfo.name} (${fieldInfo.english_name})` : item.field}
                    </div>
                    <Button type="text" disabled={index === 0} onClick={() => moveFieldUp(index)}>
                      上移
                    </Button>
                    <Button type="text" disabled={index === fields.length - 1} onClick={() => moveFieldDown(index)}>
                      下移
                    </Button>
                    <Button type="text" danger onClick={() => removeField(index)}>
                      删除
                    </Button>
                  </Flex>
                )
              })}
            </div>
          </Form.Item>
        </>
      ),
    },
    {
      title: '处理执行',
      content: (
        <>
          <Flex vertical align="center" style={{ marginTop: '20px' }}>
            <Button type="primary" loading={isPending} onClick={handleStart}>
              开始处理
            </Button>
            <AppProgressSteps
              current={progress}
              items={[
                {
                  title: '新增字段',
                  description: message[1],
                },
                {
                  title: '数据拼接',
                  description: message[2],
                },
                {
                  title: '处理结果',
                  description: message[3],
                },
              ]}
            />
          </Flex>
        </>
      ),
    },
  ]

  return (
    <>
      <Button type="primary" onClick={() => setOpen(true)}>
        数据拼接
      </Button>
      <Modal
        title={steps[current]?.title}
        open={open}
        footer={
          <Flex justify="center" gap={20}>
            {current > 0 && <Button onClick={() => setCurrent(current - 1)}>上一步</Button>}
            {current < steps.length - 1 && (
              <Button type="primary" onClick={handleNext}>
                下一步
              </Button>
            )}
            {current === steps.length - 1 && (
              <Button type="primary" disabled={isPending} onClick={handleClose}>
                关闭
              </Button>
            )}
          </Flex>
        }
        destroyOnClose
        width={800}
        onCancel={handleClose}>
        <div style={{ minHeight: 300, padding: '20px 0' }}>
          <Form form={form} labelCol={{ span: 5 }} preserve={false}>
            {steps.map((item, index) => (
              <div key={index} hidden={current !== index} style={{ marginTop: '20px' }}>
                {item.content}
              </div>
            ))}
          </Form>
        </div>
      </Modal>
    </>
  )
}
