import { useQuery, useQueryClient } from '@tanstack/react-query'
import { App, Button, Card, Descriptions, Form, InputNumber, Space } from 'antd'
import { useEffect, useState } from 'react'

import { fetchAdminWorkerHallConfig, saveAdminWorkerHallConfig } from '@/services/admin'

type HallConfigFormValues = {
  maxVisibleOrders: number
}

export default function HallConfigPanel() {
  const { message } = App.useApp()
  const queryClient = useQueryClient()
  const [form] = Form.useForm<HallConfigFormValues>()
  const [saving, setSaving] = useState(false)
  const configQuery = useQuery({
    queryKey: ['admin-worker-hall-config'],
    queryFn: fetchAdminWorkerHallConfig,
  })
  const config = configQuery.data?.data

  useEffect(() => {
    if (config) form.setFieldsValue({ maxVisibleOrders: config.maxVisibleOrders })
  }, [config, form])

  async function saveConfig(values: HallConfigFormValues) {
    setSaving(true)
    try {
      await saveAdminWorkerHallConfig({ maxVisibleOrders: Number(values.maxVisibleOrders) })
      await Promise.all([
        queryClient.invalidateQueries({ queryKey: ['admin-worker-hall-config'] }),
        queryClient.invalidateQueries({ queryKey: ['admin-worker-platform-summary'] }),
      ])
      message.success('大厅配置已保存')
    } catch (error) {
      message.error(error instanceof Error ? error.message : '保存大厅配置失败')
    } finally {
      setSaving(false)
    }
  }

  return (
    <Card title="大厅配置" bordered={false} loading={configQuery.isLoading}>
      <Space direction="vertical" size="middle" style={{ width: '100%', maxWidth: 560 }}>
        <Descriptions size="small" column={3}>
          <Descriptions.Item label="展示中">{config?.visibleOrderCount || 0}</Descriptions.Item>
          <Descriptions.Item label="等待入厅">{config?.queuedOrderCount || 0}</Descriptions.Item>
          <Descriptions.Item label="当前上限">{config?.maxVisibleOrders || '-'}</Descriptions.Item>
        </Descriptions>
        <Form form={form} layout="inline" onFinish={saveConfig}>
          <Form.Item
            name="maxVisibleOrders"
            label="大厅订单总数"
            rules={[{ required: true, message: '请输入大厅订单总数' }]}
          >
            <InputNumber min={1} max={500} precision={0} style={{ width: 160 }} />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" loading={saving}>
              保存
            </Button>
          </Form.Item>
        </Form>
      </Space>
    </Card>
  )
}
