import { useCallback, useEffect, useState } from 'react'
import {
  Button,
  Card,
  Col,
  Form,
  Input,
  Modal,
  Row,
  Space,
  Table,
  Typography,
  message,
} from 'antd'
import type { ColumnsType } from 'antd/es/table'
import { sysParamsApi } from '@/lib/api'
import { formatDate } from '@/lib/date'
import type { SysParam } from '@/types/system'

export function ParamsManagementPage() {
  const [searchForm] = Form.useForm()
  const [editForm] = Form.useForm()
  const [params, setParams] = useState<SysParam[]>([])
  const [loading, setLoading] = useState(false)
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [total, setTotal] = useState(0)
  const [modalOpen, setModalOpen] = useState(false)
  const [editingParam, setEditingParam] = useState<SysParam | null>(null)

  const reloadParams = useCallback(async () => {
    setLoading(true)
    try {
      const response = await sysParamsApi.getParamsList({
        page,
        pageSize,
        ...searchForm.getFieldsValue(),
      })
      setParams(response.data.list)
      setTotal(response.data.total)
    } finally {
      setLoading(false)
    }
  }, [page, pageSize, searchForm])

  useEffect(() => {
    reloadParams()
  }, [reloadParams])

  const openCreate = () => {
    setEditingParam(null)
    editForm.resetFields()
    setModalOpen(true)
  }

  const openEdit = (record: SysParam) => {
    setEditingParam(record)
    editForm.setFieldsValue(record)
    setModalOpen(true)
  }

  const saveParam = async () => {
    const values = await editForm.validateFields()
    if (editingParam) {
      await sysParamsApi.updateParam({ ID: editingParam.ID, ...values })
      message.success('参数已更新')
    } else {
      await sysParamsApi.createParam(values)
      message.success('参数已创建')
    }
    setModalOpen(false)
    reloadParams()
  }

  const deleteParam = (record: SysParam) => {
    Modal.confirm({
      title: `删除参数 ${record.key}`,
      okButtonProps: { danger: true },
      onOk: async () => {
        await sysParamsApi.deleteParam(record.ID)
        message.success('参数已删除')
        reloadParams()
      },
    })
  }

  const columns: ColumnsType<SysParam> = [
    {
      title: '创建时间',
      width: 180,
      render: (_, record) => formatDate(record.CreatedAt),
    },
    { title: '参数名称', dataIndex: 'name', width: 160 },
    { title: '参数键', dataIndex: 'key', width: 180 },
    { title: '参数值', dataIndex: 'value' },
    { title: '说明', dataIndex: 'desc', width: 200 },
    {
      title: '操作',
      key: 'actions',
      width: 180,
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => openEdit(record)}>
            编辑
          </Button>
          <Button danger type="link" onClick={() => deleteParam(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ]

  return (
    <div className="page-stack">
      <Card className="glass-panel page-panel">
        <div className="section-heading">
          <div>
            <Typography.Title level={2} style={{ marginBottom: 8 }}>
              参数管理
            </Typography.Title>
            <Typography.Paragraph className="text-muted" style={{ marginBottom: 0 }}>
              当前页维护运行期键值参数，保持与原系统的参数读取方式一致。
            </Typography.Paragraph>
          </div>
          <Button type="primary" onClick={openCreate}>
            新建参数
          </Button>
        </div>
        <Form form={searchForm} layout="vertical" onFinish={() => { setPage(1); reloadParams() }}>
          <Row gutter={16}>
            <Col xs={24} md={8}>
              <Form.Item name="name" label="参数名称">
                <Input />
              </Form.Item>
            </Col>
            <Col xs={24} md={8}>
              <Form.Item name="key" label="参数键">
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Space>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button
              onClick={() => {
                searchForm.resetFields()
                setPage(1)
                reloadParams()
              }}
            >
              重置
            </Button>
          </Space>
        </Form>
      </Card>
      <Card className="glass-panel page-panel">
        <Table
          rowKey="ID"
          loading={loading}
          columns={columns}
          dataSource={params}
          pagination={{
            current: page,
            pageSize,
            total,
            showSizeChanger: true,
            onChange: (nextPage, nextPageSize) => {
              setPage(nextPage)
              setPageSize(nextPageSize)
            },
          }}
        />
      </Card>

      <Modal
        open={modalOpen}
        title={editingParam ? '编辑参数' : '新建参数'}
        onCancel={() => setModalOpen(false)}
        onOk={saveParam}
      >
        <Form form={editForm} layout="vertical">
          <Form.Item name="name" label="参数名称" rules={[{ required: true, message: '请输入参数名称' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="key" label="参数键" rules={[{ required: true, message: '请输入参数键' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="value" label="参数值" rules={[{ required: true, message: '请输入参数值' }]}>
            <Input.TextArea rows={4} />
          </Form.Item>
          <Form.Item name="desc" label="说明">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
