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

export default function ButtonModal() {
  const { data = { list: [] } } = useDataQuery()
  const { fieldOptions, getFieldName } = useDataFieldQuery()

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

  const field = Form.useWatch('field', form)

  useEffect(() => {
    if (field && data.list?.length) {
      const uniqList = uniqBy(data.list, field)
      setDataSource(
        uniqList.map((item: any, index) => ({
          key: index + 1,
          raw_value: item[field] || '',
          new_value: '',
        }))
      )
    }
  }, [field, data.list])

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

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

  const { mutate, isPending, progress, message, remove } = useProcessData()

  // 开始处理
  const handleStart = () => {
    const values = form.getFieldsValue()
    const rule = dataSource.reduce((result, item) => {
      return { ...result, [item.raw_value]: item.new_value }
    }, {})
    const params = { ...values, rule: JSON.stringify(rule) }
    mutate(params, {
      onSuccess: handleClose,
    })
  }

  // 关闭并重置
  const handleClose = () => {
    setOpen(false)
    setCurrent(0)
    remove()
  }
  // 步骤定义
  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="field" rules={[{ required: true, message: '请选择值映射字段' }]}>
            <Radio.Group>
              <Row gutter={[10, 10]}>
                {fieldOptions.map((item) => (
                  <Col span={8} key={item.value}>
                    <Radio value={item.value}>{item.label}</Radio>
                  </Col>
                ))}
              </Row>
            </Radio.Group>
          </Form.Item>
        </>
      ),
    },
    {
      title: '配置值映射规则',
      content: (
        <>
          <Form.Item label="值映射操作字段">{getFieldName(field)}</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: 'new_value',
                  align: 'center',
                  render: (_, record) => (
                    <Input
                      value={record.new_value}
                      onChange={(e) => handleValueChange(e.target.value, record.key)}
                      placeholder="请输入映射值"
                    />
                  ),
                },
              ]}
              dataSource={dataSource}
            />
          </Form.Item>
        </>
      ),
    },
    {
      title: '处理执行',
      content: (
        <>
          <Flex vertical align="center" style={{ marginTop: '20px' }}>
            <Button type="primary" onClick={handleStart} loading={isPending}>
              开始处理
            </Button>
            <AppProgressSteps
              current={progress}
              items={[
                { title: '新建字段' },
                { title: '复制数据' },
                { title: '值映射处理' },
                { 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 === 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} disabled={isPending}>
                关闭
              </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>
    </>
  )
}
