import { useEffect, useState } from 'react'
import { Button, Flex, Modal, Radio, Input, Form, Row, Col, Table, message } from 'antd'
import { useDataQuery, useDataFieldQuery } from '@/hooks/useQuery'
import AppProgressSteps from '@/components/AppProgressSteps'
import { uniqBy } from 'lodash-es'

export default function ButtonModal() {
  const { data = { list: [] } } = useDataQuery() // 添加默认值防止 data 为 undefined
  const { data: fields = [] } = useDataFieldQuery()

  const [open, setOpen] = useState(false)
  const [current, setCurrent] = useState(0)
  const [form] = Form.useForm()
  const [dataSource, setDataSource] = useState<{ key: number; raw_value: string; mapping_value: string }[]>([])
  const [step, setStep] = useState(-1)

  // 使用 Form.useWatch 监听表单值变化
  const checked = Form.useWatch('checked', form)

  // 当 checked 或 data 变化时更新数据源
  useEffect(() => {
    if (checked && data.list?.length) {
      const uniqList = uniqBy(data.list, checked)
      setDataSource(
        uniqList.map((item: any, index) => ({
          key: index + 1,
          raw_value: item[checked] || '',
          mapping_value: '',
        }))
      )
    }
  }, [checked, data.list])

  // 处理映射值变化
  const handleMappingValueChange = (value: string, key: number) => {
    setDataSource((prevDataSource) =>
      prevDataSource.map((item) => (item.key === key ? { ...item, mapping_value: value } : item))
    )
  }

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

  // 步骤定义
  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="checked" rules={[{ required: true, message: '请选择值映射字段' }]}>
            <Radio.Group>
              <Row gutter={[10, 10]}>
                {fields.map((item) => (
                  <Col span={8} key={item.english_name}>
                    <Radio value={item.english_name}>{item.name}</Radio>
                  </Col>
                ))}
              </Row>
            </Radio.Group>
          </Form.Item>
        </>
      ),
    },
    {
      title: '配置值映射规则',
      content: (
        <>
          <Form.Item label="值映射操作字段">{checked}</Form.Item>
          <Form.Item>
            <Table
              bordered
              pagination={{ pageSize: 10 }}
              columns={[
                { title: '序号', dataIndex: 'key', align: 'center', width: 80 },
                { title: '原始值', dataIndex: 'raw_value', align: 'center' },
                {
                  title: '映射值',
                  dataIndex: 'mapping_value',
                  align: 'center',
                  render: (_, record) => (
                    <Input
                      value={record.mapping_value}
                      onChange={(e) => handleMappingValueChange(e.target.value, record.key)}
                      placeholder="请输入映射值"
                    />
                  ),
                },
              ]}
              dataSource={dataSource}
            />
          </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 />
                      值映射处理
                    </>
                  ),
                },
                {
                  title: (
                    <>
                      第四步
                      <br />
                      处理结果
                    </>
                  ),
                  description: (
                    <>
                      累计处理{dataSource.length}个字段
                      <br />
                      累计处理{data.list?.length || 0}条记录
                    </>
                  ),
                },
              ]}
            />
          </Flex>
        </>
      ),
    },
  ]

  // 处理下一步按钮逻辑
  const handleNext = async () => {
    try {
      if (current === 0) {
        // 第一步验证表单
        await form.validateFields(['name', 'english_name', 'checked'])
      }
      setCurrent(current + 1)
    } catch (error) {
      // 表单验证错误处理
      console.error('表单验证失败', error)
    }
  }

  // 重置状态
  const handleClose = () => {
    setOpen(false)
    setCurrent(0)
    setStep(-1)
    form.resetFields()
    setDataSource([])
  }

  return (
    <>
      <Button type="primary" onClick={() => setOpen(true)}>
        值映射
      </Button>
      <Modal
        title={steps[current]?.title}
        open={open}
        footer={
          <Flex justify="center" gap={20}>
            {current === 1 && <Button type="primary">AI智能建议</Button>}
            {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={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>
    </>
  )
}
