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 { formatMoney, formatWorkerStatus } from './shared'

export default function WorkersPanel() {
  const { message } = App.useApp()
  const queryClient = useQueryClient()
  const [status, setStatus] = useState('')
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(ADMIN_DEFAULT_PAGE_SIZE)
  const [creditWorker, setCreditWorker] = useState<WorkerUser | null>(null)
  const [levelWorker, setLevelWorker] = useState<WorkerUser | null>(null)
  const [creditForm] = Form.useForm()
  const [levelForm] = Form.useForm<{ levelId?: number }>()

  const workersQuery = useQuery({
    queryKey: ['admin-worker-platform-workers', status, page, pageSize],
    queryFn: () => fetchAdminWorkerUsers({ status, page, pageSize }),
  })
  const levelsQuery = useQuery({
    queryKey: ['admin-worker-platform-levels'],
    queryFn: () => fetchAdminWorkerLevels(),
  })
  const workersPagination = workersQuery.data?.data.pagination

  async function refreshWorkers() {
    await Promise.all([
      queryClient.invalidateQueries({
        queryKey: ['admin-worker-platform-workers'],
      }),
      queryClient.invalidateQueries({
        queryKey: ['admin-worker-platform-summary'],
      }),
    ])
  }

  async function review(worker: WorkerUser, nextStatus: string) {
    try {
      await reviewAdminWorkerUser(worker.workerId, { status: nextStatus })
      message.success('打手状态已更新')
      await refreshWorkers()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '操作失败')
    }
  }

  async function submitCredit(values: { amount?: number; note?: string }) {
    if (!creditWorker) return
    try {
      await creditAdminWorkerWallet(creditWorker.workerId, {
        amount: Number(values.amount || 0),
        note: values.note,
      })
      message.success('余额已增加')
      setCreditWorker(null)
      creditForm.resetFields()
      await refreshWorkers()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '充值失败')
    }
  }

  async function submitLevel(values: { levelId?: number }) {
    if (!levelWorker) return
    try {
      await reviewAdminWorkerUser(levelWorker.workerId, {
        status: levelWorker.status,
        levelId: Number(values.levelId || 0),
        reviewNote: levelWorker.reviewNote,
      })
      message.success('打手等级已更新')
      setLevelWorker(null)
      levelForm.resetFields()
      await refreshWorkers()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '调整等级失败')
    }
  }

  const columns: TableColumnsType<WorkerUser> = [
    {
      title: '打手',
      minWidth: 220,
      render: (_, row) => (
        <div className="cell-stack">
          <Typography.Text strong>
            {row.displayName || row.username}
          </Typography.Text>
          <Typography.Text type="secondary">{row.username}</Typography.Text>
        </div>
      ),
    },
    { title: '等级', width: 140, render: (_, row) => row.level?.name || '-' },
    {
      title: '邀请人',
      width: 160,
      render: (_, row) =>
        row.inviter ? (
          <div className="cell-stack">
            <Typography.Text>{row.inviter.displayName || row.inviter.username}</Typography.Text>
            <Typography.Text type="secondary">{row.inviter.username}</Typography.Text>
          </div>
        ) : (
          '-'
        ),
    },
    {
      title: '余额',
      width: 120,
      render: (_, row) => formatMoney(row.wallet.availableAmount),
    },
    {
      title: '冻结',
      width: 120,
      render: (_, row) => formatMoney(row.wallet.frozenDepositAmount),
    },
    {
      title: '超时订单',
      width: 110,
      render: (_, row) => {
        const count = Number(row.timeoutOrderCount || 0)
        return count > 0 ? (
          <Tag color="red">{count} 单</Tag>
        ) : (
          <Typography.Text type="secondary">0</Typography.Text>
        )
      },
    },
    {
      title: '状态',
      width: 130,
      render: (_, row) => (
        <Tag color={row.status === 'active' ? 'green' : 'orange'}>
          {formatWorkerStatus(row.status)}
        </Tag>
      ),
    },
    {
      title: '操作',
      width: 340,
      render: (_, row) => (
        <Space wrap>
          {row.status !== 'active' ? (
            <Button onClick={() => review(row, 'active')}>通过</Button>
          ) : null}
          {row.status !== 'rejected' ? (
            <Button onClick={() => review(row, 'rejected')}>拒绝</Button>
          ) : null}
          <Button
            onClick={() => {
              setLevelWorker(row)
              levelForm.setFieldsValue({
                levelId: row.level?.levelId,
              })
            }}
          >
            调等级
          </Button>
          <Button onClick={() => setCreditWorker(row)}>充值</Button>
        </Space>
      ),
    },
  ]

  return (
    <Card
      title="打手"
      extra={
        <Space>
          <Select
            value={status}
            style={{ width: 150 }}
            options={[
              { value: '', label: '全部状态' },
              { value: 'pending_review', label: '待审核' },
              { value: 'active', label: '已通过' },
              { value: 'rejected', label: '已拒绝' },
              { value: 'disabled', label: '已停用' },
            ]}
            onChange={(nextStatus) => {
              setStatus(nextStatus)
              setPage(1)
            }}
          />
          <Button
            icon={<ReloadOutlined />}
            loading={workersQuery.isFetching}
            onClick={() => workersQuery.refetch()}
          >
            刷新
          </Button>
        </Space>
      }
      bordered={false}
    >
      <Table<WorkerUser>
        rowKey="workerId"
        loading={workersQuery.isLoading}
        dataSource={workersQuery.data?.data.items || []}
        columns={columns}
        pagination={buildAdminTablePagination({
          current: workersPagination?.page || page,
          pageSize: workersPagination?.pageSize || pageSize,
          total: workersPagination?.total || 0,
          onChange: (nextPage, nextPageSize) => {
            setPage(nextPage)
            setPageSize(nextPageSize)
          },
        })}
        scroll={{ x: 1000 }}
      />

      <Modal
        title="调整打手等级"
        open={Boolean(levelWorker)}
        onCancel={() => {
          setLevelWorker(null)
          levelForm.resetFields()
        }}
        onOk={() => levelForm.submit()}
        destroyOnHidden
      >
        <Form form={levelForm} layout="vertical" onFinish={submitLevel}>
          <Form.Item label="打手">
            <Typography.Text>
              {levelWorker?.displayName || levelWorker?.username || '-'}
            </Typography.Text>
          </Form.Item>
          <Form.Item
            label="目标等级"
            name="levelId"
            rules={[{ required: true, message: '请选择目标等级' }]}
          >
            <Select
              loading={levelsQuery.isLoading}
              options={(levelsQuery.data?.data.items || []).map((item) => ({
                value: item.levelId,
                label: `${item.name} / 最多同时 ${item.maxActiveOrders} 单`,
              }))}
            />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="人工增加余额"
        open={Boolean(creditWorker)}
        onCancel={() => {
          setCreditWorker(null)
          creditForm.resetFields()
        }}
        onOk={() => creditForm.submit()}
        destroyOnHidden
      >
        <Form form={creditForm} layout="vertical" onFinish={submitCredit}>
          <Form.Item
            label="金额"
            name="amount"
            rules={[{ required: true, message: '请输入金额' }]}
          >
            <InputNumber
              min={0.01}
              step={10}
              addonAfter="元"
              className="full-width"
            />
          </Form.Item>
          <Form.Item label="备注" name="note">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  )
}

