import {
  CheckOutlined,
  FormOutlined,
  PlusOutlined,
  ReloadOutlined,
  SendOutlined,
  SyncOutlined,
  TeamOutlined,
  WarningOutlined,
} from '@ant-design/icons'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import {
  App,
  Button,
  Card,
  Descriptions,
  Drawer,
  Form,
  Input,
  InputNumber,
  Modal,
  Select,
  Space,
  Statistic,
  Switch,
  Table,
  Tabs,
  Tag,
  Typography,
} from 'antd'
import type { TableColumnsType } from 'antd'
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router'

import JsonPreview from '@/components/admin/JsonPreview'
import ImageUpload from '@/components/files/ImageUpload'
import ImagePreviewList from '@/components/files/ImagePreviewList'
import PageHeader from '@/components/admin/PageHeader'
import {
  acceptAdminWorkOrder,
  createAdminMockWorkOrder,
  creditAdminWorkerWallet,
  deleteAdminWorkCategory,
  deleteAdminWorkerLevel,
  fetchAdminWorkerFinanceConfig,
  fetchAdminWorkerFinanceRequests,
  fetchAdminWorkCategories,
  fetchAdminWorkOrderSharing,
  fetchAdminWorkProductRules,
  fetchAdminWorkerLevels,
  fetchAdminWorkerPlatformSummary,
  fetchAdminWorkerUsers,
  fetchAdminWorkOrders,
  markAdminWorkOrderProblem,
  publishAdminWorkOrder,
  reviewAdminWorkerFinanceRequest,
  resolveAdminProblemWorkOrder,
  reviewAdminWorkerUser,
  saveAdminWorkerFinanceConfig,
  saveAdminWorkCategory,
  saveAdminWorkProductRule,
  saveAdminWorkerLevel,
  submitAdminWorkOrderMaterial,
  syncAdminWorkerOrdersFromSource,
  unpublishAdminWorkOrder,
  updateAdminWorkOrderSharing,
} from '@/services/admin'
import type {
  CollectField,
  UploadedFile,
  WorkCategory,
  WorkOrder,
  WorkOrderShare,
  WorkProductRule,
  WorkerFinanceConfig,
  WorkerFinanceRequest,
  WorkerLevel,
  WorkerUser,
} from '@/types/worker-platform'
import {
  ADMIN_DEFAULT_PAGE_SIZE,
  buildAdminTablePagination,
} from '@/utils/admin-pagination'
import { formatAdminDateTime } from '@/utils/admin-time'
import CategoriesPanel from './panels/CategoriesPanel'
import FinancePanel from './panels/FinancePanel'
import LevelsPanel from './panels/LevelsPanel'
import ProductRulesPanel from './panels/ProductRulesPanel'
import WorkersPanel from './panels/WorkersPanel'
import WorkOrdersPanel from './panels/WorkOrdersPanel'

export default function AdminWorkerPlatformPage() {
  const [activeTab, setActiveTab] = useState(loadActiveTabPreference)

  function changeTab(nextTab: string) {
    setActiveTab(nextTab)
    localStorage.setItem(ACTIVE_TAB_STORAGE_KEY, nextTab)
  }

  return (
    <section className="page-stack">
      <PageHeader
        title="接单平台"
        description="管理打手、接单工单、等级权限和本地 Mock 工单。"
      />
      <SummaryCards />
      <Tabs
        destroyOnHidden={false}
        activeKey={activeTab}
        onChange={changeTab}
        items={[
          { key: 'orders', label: '接单工单', children: <WorkOrdersPanel /> },
          { key: 'rules', label: '物品规则', children: <ProductRulesPanel /> },
          { key: 'categories', label: '分类', children: <CategoriesPanel /> },
          { key: 'workers', label: '打手', children: <WorkersPanel /> },
          { key: 'finance', label: '资金', children: <FinancePanel /> },
          { key: 'levels', label: '等级权限', children: <LevelsPanel /> },
        ]}
      />
    </section>
  )
}

const ACTIVE_TAB_STORAGE_KEY = 'admin-worker-platform-tab'

function loadActiveTabPreference(): string {
  const saved = localStorage.getItem(ACTIVE_TAB_STORAGE_KEY)
  return saved === 'orders' ||
    saved === 'rules' ||
    saved === 'categories' ||
    saved === 'workers' ||
    saved === 'finance' ||
    saved === 'levels'
    ? saved
    : 'orders'
}

function SummaryCards() {
  const summaryQuery = useQuery({
    queryKey: ['admin-worker-platform-summary'],
    queryFn: () => fetchAdminWorkerPlatformSummary(),
  })
  const summary = summaryQuery.data?.data

  return (
    <div className="metric-grid four">
      <Card>
        <Statistic
          title="待审核打手"
          value={summary?.pendingWorkerCount || 0}
        />
      </Card>
      <Card>
        <Statistic
          title="待完善订单"
          value={summary?.pendingMaterialCount || 0}
        />
      </Card>
      <Card>
        <Statistic title="大厅订单" value={summary?.openOrderCount || 0} />
      </Card>
      <Card>
        <Statistic title="代练中" value={summary?.inProgressOrderCount || 0} />
      </Card>
    </div>
  )
}

