import {
  ClockCircleOutlined,
  PushpinOutlined,
  QuestionCircleOutlined,
  ReloadOutlined,
  SearchOutlined,
  TrophyOutlined,
} from '@ant-design/icons'
import { useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query'
import {
  Alert,
  App,
  Button,
  Card,
  Descriptions,
  Drawer,
  Empty,
  Input,
  InputNumber,
  Modal,
  Space,
  Spin,
  Switch,
  Tabs,
  Tag,
  Tooltip,
  Typography,
} from 'antd'
import { useEffect, useRef, useState } from 'react'

import {
  fetchWorkerHallOrders,
  fetchWorkerHallLeaderboard,
  fetchWorkerMyOrders,
  fetchWorkerMyOrderOverview,
  fetchWorkerProfile,
  grabWorkerOrder,
  joinWorkerSharingOrder,
} from '@/services/worker'
import type { WorkOrder, WorkerLeaderboardPeriod, WorkerUser } from '@/types/worker-platform'
import { useIsMobile } from '@/utils/use-is-mobile'
import {
  isGrabConfirmEnabled,
  setGrabConfirmEnabled as setGrabConfirmEnabledStorage,
} from '@/utils/worker-grab-confirm'
import {
  resolveHallDepositAmount,
  resolveHallProductName,
  resolveHallRemainingQuantity,
  resolveHallRewardAmount,
} from '@/utils/worker-product-name'

type HallSummary = {
  pendingAcceptanceCount: number
  problemCount: number
}

const HALL_PAGE_SIZE = 20

export default function WorkerHallPage() {
  const isMobile = useIsMobile()
  const { message, modal } = App.useApp()
  const queryClient = useQueryClient()
  const [keywordInput, setKeywordInput] = useState('')
  const [keyword, setKeyword] = useState('')
  const [categoryId, setCategoryId] = useState(0)
  const [grabbingId, setGrabbingId] = useState(0)
  const [sharingOrder, setSharingOrder] = useState<WorkOrder | null>(null)
  const [leaderboardOpen, setLeaderboardOpen] = useState(false)
  const [leaderboardPeriod, setLeaderboardPeriod] = useState<WorkerLeaderboardPeriod>('all')
  const [sharingQuantity, setSharingQuantity] = useState(1)
  const [submittingSharing, setSubmittingSharing] = useState(false)
  const [grabConfirmEnabled, setGrabConfirmEnabled] = useState(isGrabConfirmEnabled)
  const loadMoreRef = useRef<HTMLDivElement | null>(null)

  const ordersQuery = useInfiniteQuery({
    queryKey: ['worker-hall-orders', keyword, categoryId],
    initialPageParam: 1,
    queryFn: ({ pageParam }) =>
      fetchWorkerHallOrders({
        keyword,
        page: Number(pageParam),
        pageSize: HALL_PAGE_SIZE,
        categoryId: categoryId || undefined,
      }),
    getNextPageParam: (lastPage) => {
      const pagination = lastPage.data.pagination
      return pagination.page * pagination.pageSize < pagination.total
        ? pagination.page + 1
        : undefined
    },
    staleTime: 2_000,
    refetchOnWindowFocus: false,
    retry: false,
  })

  const profileQuery = useQuery({
    queryKey: ['worker-profile'],
    queryFn: () => fetchWorkerProfile(),
    retry: false,
  })

  const hallSummaryQuery = useQuery({
    queryKey: ['worker-hall-summary'],
    queryFn: async () => {
      const response = await fetchWorkerMyOrderOverview()
      const summaryByStatus = new Map(
        response.data.items.map((item) => [item.status, item.orderCount]),
      )

      return {
        pendingAcceptanceCount: Number(summaryByStatus.get('pending_acceptance') || 0),
        problemCount: Number(summaryByStatus.get('problem') || 0),
      } satisfies HallSummary
    },
    staleTime: 5_000,
    refetchOnWindowFocus: false,
    retry: false,
  })

  const leaderboardQuery = useQuery({
    queryKey: ['worker-hall-leaderboard', leaderboardPeriod],
    queryFn: () => fetchWorkerHallLeaderboard(leaderboardPeriod),
    enabled: leaderboardOpen,
    retry: false,
  })

  const orders = ordersQuery.data?.pages.flatMap((page) => page.data.items) || []
  const firstPage = ordersQuery.data?.pages[0]?.data
  const categories = firstPage?.categories || []
  const worker = profileQuery.data?.data.worker
  const activeCount = Number(profileQuery.data?.data.summary.activeOrderCount || 0)
  const pendingAcceptanceCount = hallSummaryQuery.data?.pendingAcceptanceCount || 0
  const problemCount = hallSummaryQuery.data?.problemCount || 0
  const maxActiveOrders = Number(worker?.level?.permissions.maxActiveOrders || 0)
  const remainingSlots = maxActiveOrders > 0 ? Math.max(0, maxActiveOrders - activeCount) : null
  const shouldWarn = (remainingSlots !== null && remainingSlots <= 0) || problemCount > 0

  useEffect(() => {
    const target = loadMoreRef.current
    if (
      !target ||
      !ordersQuery.hasNextPage ||
      ordersQuery.isFetchingNextPage ||
      ordersQuery.isFetchNextPageError
    ) {
      return
    }
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0]?.isIntersecting) {
          void ordersQuery.fetchNextPage()
        }
      },
      { rootMargin: '320px 0px' },
    )
    observer.observe(target)
    return () => observer.disconnect()
  }, [
    ordersQuery.fetchNextPage,
    ordersQuery.hasNextPage,
    ordersQuery.isFetchNextPageError,
    ordersQuery.isFetchingNextPage,
  ])

  async function refreshAll() {
    await Promise.all([
      queryClient.resetQueries({ queryKey: ['worker-hall-orders'] }),
      queryClient.invalidateQueries({ queryKey: ['worker-hall-summary'] }),
      queryClient.invalidateQueries({ queryKey: ['worker-profile'] }),
      queryClient.invalidateQueries({ queryKey: ['worker-my-orders'] }),
      queryClient.invalidateQueries({ queryKey: ['worker-my-orders-overview'] }),
      queryClient.invalidateQueries({ queryKey: ['worker-hall-leaderboard'] }),
    ])
  }

  function toggleGrabConfirm(checked: boolean) {
    setGrabConfirmEnabled(checked)
    setGrabConfirmEnabledStorage(checked)
  }

  function requestGrab(order: WorkOrder) {
    if (!grabConfirmEnabled) {
      void submitGrab(order)
      return
    }
    modal.confirm({
      title: '确认抢单',
      icon: <QuestionCircleOutlined />,
      content: `确认抢下「${resolveHallProductName(order)}」？奖励 ${formatMoney(
        resolveHallRewardAmount(order),
      )}`,
      okText: '确认抢单',
      cancelText: '取消',
      onOk: () => submitGrab(order),
    })
  }

  async function submitGrab(order: WorkOrder) {
    setGrabbingId(order.workOrderId)
    try {
      await grabWorkerOrder(order.workOrderId)
      message.success('抢单成功，已进入我的订单')
      await refreshAll()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '抢单失败')
    } finally {
      setGrabbingId(0)
    }
  }

  function openSharingModal(order: WorkOrder) {
    setSharingOrder(order)
    setSharingQuantity(1)
  }

  async function submitSharing() {
    if (!sharingOrder) return
    setSubmittingSharing(true)
    try {
      await joinWorkerSharingOrder(sharingOrder.workOrderId, {
        quantity: sharingQuantity,
      })
      message.success('拼单成功，已进入我的订单')
      setSharingOrder(null)
      await refreshAll()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '拼单失败')
    } finally {
      setSubmittingSharing(false)
    }
  }

  function resolveSharingRemaining(order: WorkOrder): number {
    return resolveHallRemainingQuantity(order)
  }

  function resolveSharingDeposit(order: WorkOrder, quantity: number): number {
    const sharing = order.sharing
    if (!sharing?.enabled) return 0
    const deposit = Number(order.requiredDepositAmount || 0)
    const total = Math.max(1, sharing.totalQuantity)
    return Math.round((deposit * quantity) / total)
  }

  function applyKeywordSearch() {
    setKeyword(keywordInput.trim())
  }

  const loadMoreIndicator =
    orders.length > 0 &&
    (ordersQuery.hasNextPage ||
      ordersQuery.isFetchingNextPage ||
      ordersQuery.isFetchNextPageError) ? (
      <div ref={loadMoreRef} className="worker-hall-load-more" aria-live="polite">
        {ordersQuery.isFetchingNextPage ? <Spin size="small" /> : null}
        {ordersQuery.isFetchingNextPage ? <span>加载中</span> : null}
        {ordersQuery.isFetchNextPageError ? <span>加载失败，请刷新后重试</span> : null}
      </div>
    ) : null

  const summaryItems = [
    {
      label: '当前余额',
      value: worker ? formatMoney(worker.wallet.availableAmount) : '-',
      note: worker
        ? `冻结押金 ${formatMoney(worker.wallet.frozenDepositAmount)}`
        : '可用于抢单冻结',
    },
    {
      label: '接单上限',
      value: remainingSlots === null ? '未配置' : `${activeCount}/${maxActiveOrders} 单`,
      note:
        remainingSlots === null
          ? '当前等级待配置'
          : `待验收 ${pendingAcceptanceCount} 单 / 问题单 ${problemCount} 单（不占上限）`,
    },
  ]

  return (
    <>
      {isMobile ? (
        <div className="worker-hall-mobile-page">
          {/* 移动端顶部极简状态 & 刷新控制 */}
          <div className="worker-hall-mobile-top-bar">
            <div className="worker-hall-mobile-stat-pill">
              <span className="worker-hall-mobile-stat-item">
                余额{' '}
                <strong className="worker-hall-mobile-stat-highlight">
                  {worker ? formatMoney(worker.wallet.availableAmount) : '-'}
                </strong>
              </span>
              <span className="worker-hall-mobile-stat-divider">|</span>
              <span className="worker-hall-mobile-stat-item">
                上限{' '}
                <strong>
                  {remainingSlots === null ? '-' : `${activeCount}/${maxActiveOrders}`}
                </strong>
              </span>
            </div>

            <div className="worker-hall-mobile-top-actions">
              <Tooltip title={`抢单确认已${grabConfirmEnabled ? '开启' : '关闭'}`}>
                <Button
                  aria-label="抢单确认开关"
                  size="small"
                  shape="circle"
                  icon={<QuestionCircleOutlined />}
                  type={grabConfirmEnabled ? 'primary' : 'default'}
                  onClick={() => toggleGrabConfirm(!grabConfirmEnabled)}
                />
              </Tooltip>
              <Tooltip title="接单排行榜">
                <Button
                  aria-label="接单排行榜"
                  size="small"
                  shape="circle"
                  icon={<TrophyOutlined />}
                  onClick={() => setLeaderboardOpen(true)}
                />
              </Tooltip>
              <Button
                size="small"
                shape="circle"
                icon={<ReloadOutlined />}
                loading={
                  ordersQuery.isFetching || profileQuery.isFetching || hallSummaryQuery.isFetching
                }
                onClick={() => refreshAll()}
              />
            </div>
          </div>

          {/* 移动端横向滑动分类条 */}
          {categories.length > 0 ? (
            <div className="worker-hall-mobile-category-bar">
              <button
                type="button"
                className={`worker-hall-mobile-cat-pill ${categoryId === 0 ? 'active' : ''}`}
                onClick={() => {
                  setCategoryId(0)
                }}
              >
                全部
              </button>
              {categories.map((category) => (
                <button
                  key={category.categoryId}
                  type="button"
                  className={`worker-hall-mobile-cat-pill ${categoryId === category.categoryId ? 'active' : ''}`}
                  onClick={() => {
                    setCategoryId(category.categoryId)
                  }}
                >
                  {category.name}
                </button>
              ))}
            </div>
          ) : null}

          {/* 紧凑搜索栏 */}
          <div className="worker-hall-mobile-search-row">
            <Input
              allowClear
              value={keywordInput}
              placeholder="搜索商品 / 订单号 / 游戏ID / 游戏昵称"
              prefix={<SearchOutlined />}
              className="worker-hall-mobile-search-input"
              onChange={(event) => {
                const nextKeyword = event.target.value
                setKeywordInput(nextKeyword)
                if (!nextKeyword.trim()) {
                  setKeyword('')
                }
              }}
              onPressEnter={applyKeywordSearch}
            />
            <Button
              type="primary"
              icon={<SearchOutlined />}
              loading={ordersQuery.isFetching}
              onClick={applyKeywordSearch}
            >
              搜索
            </Button>
          </div>

          {shouldWarn ? (
            <Alert
              className="worker-hall-warning"
              showIcon
              type="warning"
              message={
                remainingSlots !== null && remainingSlots <= 0
                  ? '当前已达到接单上限，请先处理现有工单'
                  : `当前还有 ${problemCount} 单问题单待处理，建议优先收口`
              }
            />
          ) : null}

          {/* 移动端高密度订单卡片流 */}
          <div className="worker-hall-mobile-list">
            {ordersQuery.isLoading ? (
              <div className="worker-hall-loading">
                <Spin size="large" />
              </div>
            ) : ordersQuery.error && orders.length === 0 ? (
              <Empty
                description={
                  ordersQuery.error instanceof Error
                    ? ordersQuery.error.message
                    : '读取抢单大厅失败'
                }
              />
            ) : orders.length === 0 ? (
              <Empty
                description={
                  keyword
                    ? `没有找到与 “${keyword}” 相关的可抢工单`
                    : '当前暂无可抢工单，可稍后刷新再看'
                }
              />
            ) : (
              orders.map((order) => {
                const disabledReason = resolveGrabDisabledReason(order, worker, remainingSlots)
                const productName = resolveHallProductName(order) || '未命名商品'
                const sharingRemaining = resolveSharingRemaining(order)

                return (
                  <article key={order.workOrderId} className="worker-hall-mobile-card">
                    {/* 卡片头部: 分类 + 拼单/时限标签 + 订单号 */}
                    <div className="worker-hall-mobile-card-top">
                      <div className="worker-hall-mobile-card-tags">
                        {order.pinnedAt ? (
                          <Tag
                            color="gold"
                            icon={<PushpinOutlined />}
                            className="worker-hall-mobile-tag"
                          >
                            置顶
                          </Tag>
                        ) : null}
                        {order.categoryName ? (
                          <Tag color="blue" className="worker-hall-mobile-tag">
                            {order.categoryName}
                          </Tag>
                        ) : null}
                        {order.sharing?.enabled ? (
                          <Tag color="purple" className="worker-hall-mobile-tag">
                            拼单 {order.sharingProgress?.joinedQuantity || 0}/
                            {order.sharing.totalQuantity} · 剩{resolveSharingRemaining(order)}份
                          </Tag>
                        ) : null}
                        {Number(order.timeoutMinutes || 0) > 0 ? (
                          <Tag
                            color="orange"
                            icon={<ClockCircleOutlined />}
                            className="worker-hall-mobile-tag"
                          >
                            限时{order.timeoutMinutes}分
                          </Tag>
                        ) : null}
                      </div>
                      <span className="worker-hall-mobile-card-orderno">
                        {getDisplayOrderNo(order)}
                      </span>
                    </div>

                    {/* 商品标题与保证金说明 */}
                    <div className="worker-hall-mobile-card-main">
                      <strong className="worker-hall-mobile-card-title" title={productName}>
                        {productName}
                      </strong>
                      <div className="worker-hall-mobile-card-meta">
                        <span>所需保证金: {formatMoney(resolveHallDepositAmount(order))}</span>
                        {order.sharing?.enabled ? (
                          <span> · 拼单单价 {formatMoney(order.sharing.unitReward)}/份</span>
                        ) : null}
                      </div>
                    </div>

                    {/* 底部报酬金额与抢单按钮 */}
                    <div className="worker-hall-mobile-card-footer">
                      <div className="worker-hall-mobile-card-price-group">
                        <span className="worker-hall-mobile-card-price-label">接单报酬</span>
                        <strong className="worker-hall-mobile-card-price-val">
                          {formatMoney(resolveHallRewardAmount(order))}
                        </strong>
                      </div>

                      <div className="worker-hall-mobile-card-btn-group">
                        {order.sharing?.enabled &&
                        (sharingRemaining > 0 || order.myShare) &&
                        !disabledReason ? (
                          <Button
                            type="primary"
                            size="middle"
                            className="worker-hall-sharing-button"
                            disabled={Boolean(disabledReason) || Boolean(order.myShare)}
                            onClick={() => openSharingModal(order)}
                          >
                            {order.myShare
                              ? `已拼 ${order.myShare.quantity} 份`
                              : `拼单 ${formatMoney(order.sharing.unitReward)}/份`}
                          </Button>
                        ) : null}
                        {sharingRemaining > 0 || !order.sharing?.enabled ? (
                          <Button
                            type="primary"
                            size="middle"
                            className="worker-hall-mobile-grab-btn"
                            disabled={Boolean(disabledReason)}
                            loading={grabbingId === order.workOrderId}
                            onClick={() => requestGrab(order)}
                          >
                            {disabledReason || '立即抢单'}
                          </Button>
                        ) : null}
                      </div>
                    </div>
                  </article>
                )
              })
            )}

            {loadMoreIndicator}
          </div>
        </div>
      ) : (
        <section className="page-stack">
          <div className="worker-page-head">
            <div className="worker-page-head-title-row">
              <Typography.Title level={3}>抢单大厅</Typography.Title>
              <div className="worker-hall-page-actions">
                <div className="worker-hall-head-controls">
                  <Tooltip title="开启后点击抢单会先弹窗确认，防止误点">
                    <span className="worker-hall-grab-confirm-toggle">
                      抢单确认
                      <Switch
                        size="small"
                        checked={grabConfirmEnabled}
                        onChange={toggleGrabConfirm}
                      />
                    </span>
                  </Tooltip>
                  <Button
                    icon={<ReloadOutlined />}
                    loading={
                      ordersQuery.isFetching ||
                      profileQuery.isFetching ||
                      hallSummaryQuery.isFetching
                    }
                    onClick={() => refreshAll()}
                  >
                    刷新
                  </Button>
                </div>
                <div className="worker-hall-leaderboard-trigger">
                  <Tooltip title="接单排行榜">
                    <Button
                      aria-label="接单排行榜"
                      icon={<TrophyOutlined />}
                      onClick={() => setLeaderboardOpen(true)}
                    >
                      接单排行榜
                    </Button>
                  </Tooltip>
                </div>
              </div>
            </div>

            <div className="worker-hall-search-bar">
              <Space.Compact className="worker-hall-search">
                <Input
                  allowClear
                  value={keywordInput}
                  placeholder="搜索商品名称 / 订单号 / 游戏ID / 游戏昵称"
                  prefix={<SearchOutlined />}
                  onChange={(event) => {
                    const nextKeyword = event.target.value
                    setKeywordInput(nextKeyword)
                    if (!nextKeyword.trim()) {
                      setKeyword('')
                    }
                  }}
                  onPressEnter={applyKeywordSearch}
                />
                <Button
                  type="primary"
                  icon={<SearchOutlined />}
                  loading={ordersQuery.isFetching}
                  onClick={applyKeywordSearch}
                >
                  搜索
                </Button>
              </Space.Compact>
            </div>
          </div>

          <Card className="worker-hall-board-card" bordered={false}>
            <div className="worker-hall-summary-strip">
              {summaryItems.map((item) => (
                <div key={item.label} className="worker-hall-summary-item">
                  <span className="worker-hall-summary-label">{item.label}</span>
                  <strong className="worker-hall-summary-value">{item.value}</strong>
                  <small className="worker-hall-summary-note">{item.note}</small>
                </div>
              ))}
            </div>

            {categories.length > 0 ? (
              <Tabs
                size="small"
                activeKey={String(categoryId)}
                items={[
                  { key: '0', label: '全部' },
                  ...categories.map((category) => ({
                    key: String(category.categoryId),
                    label: category.name,
                  })),
                ]}
                onChange={(nextKey) => {
                  setCategoryId(Number(nextKey) || 0)
                }}
              />
            ) : null}

            {shouldWarn ? (
              <Alert
                className="worker-hall-warning"
                showIcon
                type="warning"
                message={
                  remainingSlots !== null && remainingSlots <= 0
                    ? '当前已达到接单上限，请先处理现有工单'
                    : `当前还有 ${problemCount} 单问题单待处理，建议优先收口`
                }
              />
            ) : null}

            {ordersQuery.isLoading ? (
              <div className="worker-hall-loading">
                <Spin size="large" />
              </div>
            ) : ordersQuery.error && orders.length === 0 ? (
              <Empty
                description={
                  ordersQuery.error instanceof Error
                    ? ordersQuery.error.message
                    : '读取抢单大厅失败'
                }
              />
            ) : orders.length === 0 ? (
              <Empty
                description={
                  keyword
                    ? `没有找到与 “${keyword}” 相关的可抢工单`
                    : '当前暂无可抢订单，可稍后刷新再看'
                }
              />
            ) : (
              <>
                <div className="worker-hall-card-grid">
                  {orders.map((order) => {
                    const disabledReason = resolveGrabDisabledReason(order, worker, remainingSlots)
                    const productName = resolveHallProductName(order) || '未命名商品'
                    const sharingRemaining = resolveSharingRemaining(order)

                    return (
                      <article key={order.workOrderId} className="worker-hall-card">
                        <div className="worker-hall-card-title">
                          {order.pinnedAt ? (
                            <Tag
                              color="gold"
                              icon={<PushpinOutlined />}
                              className="worker-hall-pinned-tag"
                            >
                              置顶
                            </Tag>
                          ) : null}
                          <strong className="worker-hall-card-title-text" title={productName}>
                            {productName}
                          </strong>
                          <Typography.Text type="secondary">
                            {order.categoryName || '默认分类'}
                          </Typography.Text>
                          <Typography.Text type="secondary">
                            订单号：{getDisplayOrderNo(order)}
                          </Typography.Text>
                        </div>

                        {order.sharing?.enabled ? (
                          <div className="worker-hall-card-sharing">
                            <Tag color="purple">拼单</Tag>
                            <Typography.Text type="secondary">
                              单价 {formatMoney(order.sharing.unitReward)} · 进度{' '}
                              {order.sharingProgress?.joinedQuantity || 0}/
                              {order.sharing.totalQuantity} · 剩 {resolveSharingRemaining(order)} 份
                            </Typography.Text>
                          </div>
                        ) : null}

                        {Number(order.timeoutMinutes || 0) > 0 ? (
                          <div className="worker-hall-card-sharing">
                            <Tag color="orange" icon={<ClockCircleOutlined />}>
                              限时 {order.timeoutMinutes} 分钟
                            </Tag>
                          </div>
                        ) : null}

                        <div className="worker-hall-card-amount-row">
                          <div className="worker-hall-card-amount">
                            {formatMoney(resolveHallRewardAmount(order))}
                          </div>
                          <Typography.Text type="secondary" className="worker-hall-card-deposit">
                            所需保证金：{formatMoney(resolveHallDepositAmount(order))}
                          </Typography.Text>
                        </div>

                        {disabledReason ? (
                          <Typography.Text type="danger" className="worker-hall-card-hint">
                            {disabledReason}
                          </Typography.Text>
                        ) : null}

                        <div className="worker-hall-card-actions">
                          <div className="worker-hall-card-grab-row">
                            {order.sharing?.enabled &&
                            (sharingRemaining > 0 || order.myShare) &&
                            !disabledReason ? (
                              <Button
                                type="primary"
                                size="large"
                                className="worker-hall-sharing-button"
                                disabled={Boolean(disabledReason) || Boolean(order.myShare)}
                                onClick={() => openSharingModal(order)}
                              >
                                {order.myShare
                                  ? `已拼 ${order.myShare.quantity} 份`
                                  : `拼单 ${formatMoney(order.sharing.unitReward)}/份`}
                              </Button>
                            ) : null}
                            {sharingRemaining > 0 || !order.sharing?.enabled ? (
                              <Button
                                type="primary"
                                size="large"
                                disabled={Boolean(disabledReason)}
                                loading={grabbingId === order.workOrderId}
                                onClick={() => requestGrab(order)}
                              >
                                {disabledReason || '立即抢单'}
                              </Button>
                            ) : null}
                          </div>
                        </div>
                      </article>
                    )
                  })}
                </div>

                {loadMoreIndicator}
              </>
            )}
          </Card>
        </section>
      )}

      <Modal
        title={`拼单参与 · ${sharingOrder ? resolveHallProductName(sharingOrder) : ''}`}
        width={isMobile ? '92%' : 520}
        open={Boolean(sharingOrder)}
        confirmLoading={submittingSharing}
        onCancel={() => setSharingOrder(null)}
        onOk={submitSharing}
        okText="确认拼单"
        cancelText="取消"
        okButtonProps={{ disabled: sharingQuantity <= 0 }}
      >
        {sharingOrder ? (
          <Space direction="vertical" size={16} className="full-width">
            <Alert
              showIcon
              type="info"
              message={`单价 ${formatMoney(sharingOrder.sharing?.unitReward || 0)} / 份，剩余 ${resolveSharingRemaining(sharingOrder)} 份可拼`}
            />
            <Descriptions column={1} bordered size="small">
              <Descriptions.Item label="拼单进度">
                {sharingOrder.sharingProgress?.joinedQuantity || 0} /{' '}
                {sharingOrder.sharing?.totalQuantity || 0} 份
              </Descriptions.Item>
              <Descriptions.Item label="参与数量">
                <InputNumber
                  min={1}
                  max={resolveSharingRemaining(sharingOrder)}
                  value={sharingQuantity}
                  onChange={(value) => setSharingQuantity(Number(value) || 1)}
                  addonAfter="份"
                />
              </Descriptions.Item>
              <Descriptions.Item label="预估报酬">
                {formatMoney((sharingOrder.sharing?.unitReward || 0) * sharingQuantity)}
              </Descriptions.Item>
              <Descriptions.Item label="预估冻结押金">
                {formatMoney(resolveSharingDeposit(sharingOrder, sharingQuantity))}
              </Descriptions.Item>
            </Descriptions>
          </Space>
        ) : null}
      </Modal>

      <Drawer
        title={
          <Space size={8}>
            <TrophyOutlined className="worker-hall-leaderboard-title-icon" />
            <span>接单排行榜</span>
          </Space>
        }
        open={leaderboardOpen}
        placement="right"
        width={isMobile ? '88vw' : 360}
        onClose={() => setLeaderboardOpen(false)}
      >
        <div className="worker-hall-leaderboard">
          <Tabs
            activeKey={leaderboardPeriod}
            className="worker-hall-leaderboard-tabs"
            items={[
              { key: 'all', label: '总榜' },
              { key: 'daily', label: '每日榜' },
            ]}
            onChange={(key) => setLeaderboardPeriod(key === 'daily' ? 'daily' : 'all')}
          />
          <Typography.Text type="secondary" className="worker-hall-leaderboard-caption">
            {leaderboardPeriod === 'daily'
              ? '按今日验收完成数量排行（北京时间）'
              : '按累计验收完成数量排行'}
          </Typography.Text>
          {leaderboardQuery.isLoading ? (
            <div className="worker-hall-leaderboard-loading">
              <Spin />
            </div>
          ) : leaderboardQuery.error ? (
            <Typography.Text type="danger">
              {leaderboardQuery.error instanceof Error
                ? leaderboardQuery.error.message
                : '排行榜读取失败'}
            </Typography.Text>
          ) : (leaderboardQuery.data?.data.items.length || 0) > 0 ? (
            <div className="worker-hall-leaderboard-list">
              {leaderboardQuery.data?.data.items.map((entry) => (
                <div
                  key={entry.workerId}
                  className={`worker-hall-leaderboard-row ${
                    entry.workerId === worker?.workerId ? 'is-current' : ''
                  }`}
                >
                  <span className={`worker-hall-leaderboard-rank rank-${Math.min(entry.rank, 3)}`}>
                    {entry.rank}
                  </span>
                  <div className="worker-hall-leaderboard-worker">
                    <Typography.Text strong ellipsis>
                      {entry.displayName || '未命名打手'}
                    </Typography.Text>
                  </div>
                  <Typography.Text strong className="worker-hall-leaderboard-count">
                    {entry.acceptedOrderCount} 单
                  </Typography.Text>
                </div>
              ))}
            </div>
          ) : (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无完成订单" />
          )}
          {leaderboardQuery.data ? (
            <div className="worker-hall-leaderboard-current">
              <Typography.Text type="secondary">我的排名</Typography.Text>
              <Typography.Text strong>
                {leaderboardQuery.data.data.current.rank
                  ? `第 ${leaderboardQuery.data.data.current.rank} 名`
                  : '暂未上榜'}
              </Typography.Text>
              <Typography.Text type="secondary">
                已完成 {leaderboardQuery.data.data.current.acceptedOrderCount} 单
              </Typography.Text>
            </div>
          ) : null}
        </div>
      </Drawer>
    </>
  )
}

function resolveGrabDisabledReason(
  order: WorkOrder,
  worker: WorkerUser | undefined,
  remainingSlots: number | null,
) {
  if (remainingSlots !== null && remainingSlots <= 0 && !order.myShare) {
    return '已达到当前等级最大同时接单量'
  }

  if (!worker) {
    return ''
  }

  const availableAmount = Number(worker.wallet.availableAmount || 0)
  const freezeAmount = resolveHallDepositAmount(order)
  if (availableAmount < freezeAmount) {
    return `余额不足，还差 ${formatMoney(freezeAmount - availableAmount)}`
  }

  return ''
}

function getDisplayOrderNo(order: Pick<WorkOrder, 'platformOrderId'> | null | undefined): string {
  return String(order?.platformOrderId || '').trim() || '-'
}

function formatMoney(value: number | undefined) {
  return `￥${((Number(value || 0) || 0) / 100).toFixed(2)}`
}
