import { useQuery } from '@tanstack/react-query'
import { Card, Space, Tabs } from 'antd'
import { useEffect, useRef, useState } from 'react'
import { useLocation, useSearchParams } from 'react-router'

import PageHeader from '@/components/admin/PageHeader'
import type { WorkOrder } from '@/types/worker-platform'
import { fetchAdminWorkerPlatformSummary } from '@/services/admin'
import { getAdminRole } from '@/utils/admin-auth'
import AfterSalesPanel, { type AfterSalesPanelHandle } from './panels/AfterSalesPanel'
import AnnouncementPanel from './panels/AnnouncementPanel'
import CancelRequestsPanel from './panels/CancelRequestsPanel'
import CategoriesPanel from './panels/CategoriesPanel'
import FeedbacksPanel from './panels/FeedbacksPanel'
import FinancePanel from './panels/FinancePanel'
import LeaderboardPanel from './panels/LeaderboardPanel'
import LevelsPanel from './panels/LevelsPanel'
import NotificationsPanel from './panels/NotificationsPanel'
import ProductMatchPanel from './panels/ProductMatchPanel'
import ProductRulesPanel from './panels/ProductRulesPanel'
import WorkersPanel from './panels/WorkersPanel'
import WorkOrdersPanel from './panels/WorkOrdersPanel'

type AfterSalesLocationState = {
  createOrder?: WorkOrder
}

export default function AdminWorkerPlatformPage() {
  const [searchParams, setSearchParams] = useSearchParams()
  const location = useLocation()
  const [activeTab, setActiveTab] = useState(() => loadActiveTab(searchParams.get('tab')))
  const afterSalesPanelRef = useRef<AfterSalesPanelHandle>(null)
  const role = getAdminRole()
  const isAdmin = role === 'admin'
  const isSupport = role === 'support'
  const isFinance = role === 'finance'
  const visibleActiveTab = isFinance
    ? 'finance'
    : !isAdmin && activeTab === 'notifications'
      ? 'orders'
      : activeTab

  useEffect(() => {
    const tab = searchParams.get('tab')
    if (isWorkerPlatformTab(tab)) {
      setActiveTab(tab)
    }
  }, [searchParams])

  useEffect(() => {
    const state = location.state as AfterSalesLocationState | null
    if (state?.createOrder) {
      setActiveTab('after-sales')
      afterSalesPanelRef.current?.openCreateModal(state.createOrder)
      // 清掉 state，避免刷新或后退时重复弹窗。
      window.history.replaceState({}, '')
    }
  }, [location.state])

  function changeTab(nextTab: string) {
    if (!isWorkerPlatformTab(nextTab)) return
    if (isFinance && nextTab !== 'finance') return
    setActiveTab(nextTab)
    localStorage.setItem(ACTIVE_TAB_STORAGE_KEY, nextTab)
    setSearchParams(
      (current) => {
        current.set('tab', nextTab)
        return current
      },
      { replace: true },
    )
  }

  const afterSalesTab = {
    key: 'after-sales',
    label: '售后问题单',
    children: <AfterSalesPanel ref={afterSalesPanelRef} />,
  }

  return (
    <section className="page-stack">
      <PageHeader
        title="接单平台"
        description="管理打手、接单工单、等级权限、售后追责和本地 Mock 工单。"
      />
      {!isFinance ? <SummaryCards /> : null}
      <Tabs
        destroyOnHidden={false}
        activeKey={visibleActiveTab}
        onChange={changeTab}
        items={
          isFinance
            ? [{ key: 'finance', label: '资金审核', children: <FinancePanel /> }]
            : isSupport
              ? [
                  { key: 'orders', label: '接单工单', children: <WorkOrdersPanel /> },
                  {
                    key: 'cancel-requests',
                    label: '打手退单审核',
                    children: <CancelRequestsPanel />,
                  },
                  { key: 'feedbacks', label: '问题反馈', children: <FeedbacksPanel /> },
                  afterSalesTab,
                ]
              : [
                  { key: 'orders', label: '接单工单', children: <WorkOrdersPanel /> },
                  {
                    key: 'cancel-requests',
                    label: '打手退单审核',
                    children: <CancelRequestsPanel />,
                  },
                  { key: 'feedbacks', label: '问题反馈', children: <FeedbacksPanel /> },
                  afterSalesTab,
                  ...(isAdmin
                    ? [{ key: 'announcement', label: '杂项配置', children: <AnnouncementPanel /> }]
                    : []),
                  { key: 'rules', label: '接单模板', children: <ProductRulesPanel /> },
                  { key: 'product-match', label: '匹配诊断', children: <ProductMatchPanel /> },
                  { key: 'categories', label: '分类', children: <CategoriesPanel /> },
                  { key: 'workers', label: '打手', children: <WorkersPanel /> },
                  { key: 'leaderboard', label: '排行榜', children: <LeaderboardPanel /> },
                  { key: 'finance', label: '资金', children: <FinancePanel /> },
                  { key: 'levels', label: '等级权限', children: <LevelsPanel /> },
                  ...(isAdmin
                    ? [
                        {
                          key: 'notifications',
                          label: '通知配置',
                          children: <NotificationsPanel />,
                        },
                      ]
                    : []),
                ]
        }
      />
    </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 === 'leaderboard' ||
    saved === 'cancel-requests' ||
    saved === 'feedbacks' ||
    saved === 'after-sales' ||
    saved === 'announcement' ||
    saved === 'rules' ||
    saved === 'product-match' ||
    saved === 'categories' ||
    saved === 'workers' ||
    saved === 'finance' ||
    saved === 'levels' ||
    saved === 'notifications'
    ? saved
    : 'orders'
}

function loadActiveTab(tab: string | null): string {
  return isWorkerPlatformTab(tab) ? tab : loadActiveTabPreference()
}

function isWorkerPlatformTab(tab: string | null): tab is string {
  return [
    'orders',
    'leaderboard',
    'cancel-requests',
    'feedbacks',
    'after-sales',
    'announcement',
    'rules',
    'product-match',
    'categories',
    'workers',
    'finance',
    'levels',
    'notifications',
  ].includes(String(tab || ''))
}

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

  const items = [
    { label: '待处理打手', value: summary?.pendingWorkerCount || 0 },
    { label: '待完善订单', value: summary?.pendingMaterialCount || 0 },
    {
      label: '大厅展示',
      value: `${summary?.openOrderCount || 0}/${summary?.hallMaxVisibleOrders || 0}`,
    },
    { label: '等待入厅', value: summary?.queuedHallOrderCount || 0 },
    { label: '代练中', value: summary?.inProgressOrderCount || 0 },
  ]

  return (
    <Card size="small" bordered={false} className="platform-summary-strip-card">
      <Space size={32} wrap>
        {items.map((item) => (
          <span key={item.label} className="platform-summary-strip-item">
            {item.label}
            <strong>{item.value}</strong>
          </span>
        ))}
      </Space>
    </Card>
  )
}
