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

export default function ButtonModal() {
  const { data = { list: [] } } = useDataQuery() // Default value to prevent data being undefined
  const { data: fields = [] } = useDataFieldQuery()

  const [open, setOpen] = useState(false)
  const [current, setCurrent] = useState(0)
  const [form] = Form.useForm()
  const [step, setStep] = useState(-1)
  const [concatenatedFields, setConcatenatedFields] = useState<{ field: string; order: number }[]>([])

  // Process the concatenation
  const handleStart = () => {
    setStep(0)
    // Simulate processing steps with timeouts
    setTimeout(() => {
      setStep(1)
      setTimeout(() => {
        setStep(3)
        message.success('数据拼接处理完成！')
      }, 1000)
    }, 1000)
  }

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

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

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

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

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

    setConcatenatedFields(newFields)
  }

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

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

    setConcatenatedFields(newFields)
  }

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

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

    setConcatenatedFields(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: '请选择拼接新字段类型' }]}>
            <Radio.Group options={[{ label: '文本', value: 'text' }]} />
          </Form.Item>
          <Form.Item
            label="请选择数据拼接字段"
            name="selectedFields"
            rules={[
              {
                required: true,
                message: '请添加至少一个拼接字段',
                validator: () =>
                  concatenatedFields.length > 0 ? Promise.resolve() : Promise.reject('请添加至少一个拼接字段'),
              },
            ]}>
            <div>
              <Flex gap={10}>
                <Form.Item name="fieldToAdd" noStyle>
                  <Select
                    placeholder="选择要添加的字段"
                    options={fields.map((item) => ({
                      label: `${item.name} (${item.english_name})`,
                      value: item.english_name,
                    }))}
                  />
                </Form.Item>
                <Button type="primary" onClick={addConcatenationField}>
                  添加拼接字段
                </Button>
              </Flex>

              {concatenatedFields.map((item, index) => {
                const fieldInfo = fields.find((f) => f.english_name === 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 === concatenatedFields.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" onClick={handleStart} disabled={step >= 0}>
              开始处理
            </Button>
            <AppProgressSteps
              style={{ margin: '80px' }}
              current={step}
              items={[
                {
                  title: (
                    <>
                      第一步
                      <br />
                      新增字段
                    </>
                  ),
                },
                {
                  title: (
                    <>
                      第二步
                      <br />
                      数据拼接
                    </>
                  ),
                },
                {
                  title: (
                    <>
                      第三步
                      <br />
                      处理结果
                    </>
                  ),
                  description: (
                    <>
                      累计处理{concatenatedFields.length}个字段
                      <br />
                      累计处理{data.list?.length || 0}条记录
                    </>
                  ),
                },
              ]}
            />
          </Flex>
        </>
      ),
    },
  ]

  // Handle next button logic
  const handleNext = async () => {
    try {
      if (current === 0) {
        // Validate the first step form
        await form.validateFields(['name', 'english_name', 'fieldType', 'selectedFields'])
      }
      setCurrent(current + 1)
    } catch (error) {
      // Form validation error handling
      console.error('表单验证失败', error)
    }
  }

  // Reset everything when modal closes
  const handleCancel = () => {
    setOpen(false)
    setCurrent(0)
    setStep(-1)
    setConcatenatedFields([])
    form.resetFields()
  }

  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" onClick={handleCancel}>
                关闭
              </Button>
            )}
          </Flex>
        }
        destroyOnClose
        width={800}
        onCancel={handleCancel}>
        <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>
    </>
  )
}
