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

import {
  fetchAdminWorkCategories,
  fetchAdminWorkerHallConfig,
  saveAdminWorkerHallConfig,
} from '@/services/admin'
import type { WorkCategory } from '@/types/worker-platform'

type HallConfigFormValues = {
  maxVisibleOrders: number
  categoryMaxVisibleOrders: Record<string, 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,
        categoryMaxVisibleOrders: config.categoryMaxVisibleOrders || {},
      })
    }
  }, [config, form])
  const categoriesQuery = useQuery({
    queryKey: ['admin-worker-platform-categories'],
    queryFn: fetchAdminWorkCategories,
  })

  async function saveConfig(values: HallConfigFormValues) {
    setSaving(true)
    try {
      await saveAdminWorkerHallConfig({
        maxVisibleOrders: Number(values.maxVisibleOrders),
        categoryMaxVisibleOrders: values.categoryMaxVisibleOrders || {},
      })
      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="vertical" 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>
          <div>
            <Tag color="blue">分类上限</Tag>
            <span style={{ marginLeft: 8, color: '#666' }}>
              未填写的分类沿用大厅总上限；填写后仅限制该分类最多展示数量。
            </span>
          </div>
          <Table<WorkCategory>
            rowKey="categoryId"
            size="small"
            pagination={false}
            loading={categoriesQuery.isLoading}
            dataSource={categoriesQuery.data?.data.items || []}
            columns={[
              { title: '分类', dataIndex: 'name' },
              {
                title: '状态',
                render: (_, category) => (
                  <Tag color={category.status === 'active' ? 'green' : 'default'}>
                    {category.status === 'active' ? '启用' : '停用'}
                  </Tag>
                ),
              },
              {
                title: '最多展示',
                render: (_, category) => (
                  <Form.Item
                    name={['categoryMaxVisibleOrders', String(category.categoryId)]}
                    style={{ margin: 0 }}
                  >
                    <InputNumber min={1} max={500} precision={0} placeholder="跟随总上限" />
                  </Form.Item>
                ),
              },
            ]}
          />
        </Form>
      </Space>
    </Card>
  )
}
