import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from 'react-router'
import { App, Badge, Button, Form, Space, Typography } from 'antd'
import { useState } from 'react'

import {
  fetchWorkerAfterSalesCases,
  fetchWorkerCancelRequests,
  fetchWorkerOrderFeedbacks,
  fetchWorkerMyOrderOverview,
  fetchWorkerMyOrders,
  fetchWorkerProfile,
  markWorkerOrderRead,
  remindWorkerAcceptance,
  saveWorkerAcceptanceDraft,
  saveWorkerOrderNote,
  submitWorkerAcceptance,
  submitWorkerCancelRequest,
  submitWorkerGiftMaterial,
  submitWorkerOrderFeedback,
  supplementWorkerAcceptedOrderEvidence,
} from '@/services/worker'
import type { UploadedFile, WorkOrder } from '@/types/worker-platform'
import { useIsMobile } from '@/utils/use-is-mobile'
import { buildWorkerOrderQuery } from '@/utils/worker-order-query'
import { WorkerOrderDesktopList } from './WorkerOrderDesktopList'
import { WorkerOrderDetailDrawer } from './WorkerOrderDetailDrawer'
import { WorkerOrderMobileList } from './WorkerOrderMobileList'
import {
  type AcceptanceFormValues,
  type CancelRequestFormValues,
  type FeedbackFormValues,
  type GiftMaterialFormValues,
  type WorkerNoteFormValues,
  WorkerOrderModals,
} from './WorkerOrderModals'
import { buildWorkerOrderTableColumns } from './WorkerOrderTableColumns'
import {
  canAutoAcceptOrder,
  canSupplementAcceptedEvidence,
  getCopyOrderInfoItems,
  getMaterialScreenshots,
  getUniqueAcceptanceFiles,
  getWorkerAcceptance,
  getWorkerDraft,
  hasSubmittedAcceptance,
  isGiftSubmissionBlocked,
  patchWorkOrderReadState,
  toPngBlob,
} from './worker-order-utils'

const STATUS_OPTIONS = [
  { value: 'in_progress', label: '代练中' },
  { value: 'pending_acceptance', label: '待验收' },
  { value: 'problem', label: '问题单' },
  { value: 'open', label: '已超时' },
  { value: 'vip_evidence_pending', label: '待补图' },
  { value: 'accepted', label: '已验收' },
  { value: 'cancelled', label: '已取消' },
  { value: '', label: '全部订单' },
] as const

type NoteTheme = 'success' | 'processing' | 'danger' | 'warning' | 'purple' | 'default'

function resolveNoteTheme(note?: string): NoteTheme {
  const text = String(note || '')
    .trim()
    .toLowerCase()
  if (!text) return 'default'

  // 1. 危险 / 异常 / 问题类 (Red)
  if (
    text.includes('问题') ||
    text.includes('异常') ||
    text.includes('密码') ||
    text.includes('封号') ||
    text.includes('错误') ||
    text.includes('无法') ||
    text.includes('投诉') ||
    text.includes('退') ||
    text.includes('失败') ||
    text.includes('被挤')
  ) {
    return 'danger'
  }

  // 2. 暂缓 / 未安排 / 延后 / 暂停类 (Orange)
  if (
    text.includes('未安排') ||
    text.includes('未') ||
    text.includes('暂缓') ||
    text.includes('暂停') ||
    text.includes('稍后') ||
    text.includes('延后') ||
    text.includes('挂起') ||
    text.includes('待定')
  ) {
    return 'warning'
  }

  // 3. 排队 / 等待类 (Purple)
  if (
    text.includes('排队') ||
    text.includes('等待') ||
    text.includes('等买家') ||
    text.includes('等扫码') ||
    text.includes('等验证') ||
    text.includes('待扫')
  ) {
    return 'purple'
  }

  // 4. 进行中 / 打单中 / 上号 (Blue)
  if (
    text.includes('打单') ||
    text.includes('做单') ||
    text.includes('进行') ||
    text.includes('处理') ||
    text.includes('上号') ||
    text.includes('练级') ||
    text.includes('正在') ||
    text.includes('开打') ||
    text.includes('肝')
  ) {
    return 'processing'
  }

  // 5. 已安排 / 已就绪 / 完成 / 正常 (Green)
  if (
    text.includes('已安排') ||
    text.includes('安排') ||
    text.includes('已就绪') ||
    text.includes('就绪') ||
    text.includes('已联系') ||
    text.includes('完成') ||
    text.includes('已好') ||
    text.includes('搞定') ||
    text.includes('正常') ||
    text.includes('ok')
  ) {
    return 'success'
  }

  return 'default'
}

export default function WorkerOrdersPage() {
  const isMobile = useIsMobile()
  const { message } = App.useApp()
  const queryClient = useQueryClient()
  const navigate = useNavigate()
  const afterSalesQuery = useQuery({
    queryKey: ['worker-after-sales-cases'],
    queryFn: fetchWorkerAfterSalesCases,
    retry: false,
  })
  const afterSalesPendingCount = (afterSalesQuery.data?.data.items || []).filter(
    (item) => item.status === 'awaiting_worker_response',
  ).length
  const [status, setStatus] = useState('in_progress')
  const [keywordInput, setKeywordInput] = useState('')
  const [keyword, setKeyword] = useState('')
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(20)
  const [detailOrder, setDetailOrder] = useState<WorkOrder | null>(null)
  const [editingOrder, setEditingOrder] = useState<WorkOrder | null>(null)
  const [noteOrder, setNoteOrder] = useState<WorkOrder | null>(null)
  const [cancelRequestOrder, setCancelRequestOrder] = useState<WorkOrder | null>(null)
  const [feedbackOrder, setFeedbackOrder] = useState<WorkOrder | null>(null)
  const [acceptanceFiles, setAcceptanceFiles] = useState<UploadedFile[]>([])
  const [giftMaterialOrder, setGiftMaterialOrder] = useState<WorkOrder | null>(null)
  const [giftMaterialFiles, setGiftMaterialFiles] = useState<UploadedFile[]>([])
  const [form] = Form.useForm<AcceptanceFormValues>()
  const [giftMaterialForm] = Form.useForm<GiftMaterialFormValues>()
  const [noteForm] = Form.useForm<WorkerNoteFormValues>()
  const [cancelRequestForm] = Form.useForm<CancelRequestFormValues>()
  const [feedbackForm] = Form.useForm<FeedbackFormValues>()

  const ordersQuery = useQuery({
    queryKey: ['worker-my-orders', status, keyword, page, pageSize],
    queryFn: () => fetchWorkerMyOrders(buildWorkerOrderQuery(status, keyword, page, pageSize)),
    staleTime: 2_000,
    refetchOnWindowFocus: false,
    retry: false,
  })
  const pagination = ordersQuery.data?.data.pagination
  const orders = ordersQuery.data?.data.items || []

  // 流转记录对打手是否可见（后台配置开关，默认关闭）
  const profileQuery = useQuery({
    queryKey: ['worker-profile'],
    queryFn: () => fetchWorkerProfile(),
    retry: false,
  })
  const orderTimelineVisible = profileQuery.data?.data.orderTimelineVisible === true
  const workerCanAutoAcceptWithoutEvidence =
    profileQuery.data?.data.worker.level?.permissions.autoAcceptWithoutEvidence === true

  const overviewQuery = useQuery({
    queryKey: ['worker-my-orders-overview'],
    queryFn: fetchWorkerMyOrderOverview,
    staleTime: 5_000,
    refetchOnWindowFocus: false,
    retry: false,
  })
  const cancelRequestsQuery = useQuery({
    queryKey: ['worker-cancel-requests'],
    queryFn: fetchWorkerCancelRequests,
    retry: false,
  })
  const feedbacksQuery = useQuery({
    queryKey: ['worker-order-feedbacks'],
    queryFn: fetchWorkerOrderFeedbacks,
    retry: false,
  })
  const overviewByStatus = new Map(
    (overviewQuery.data?.data.items || []).map((item) => [item.status, item]),
  )

  async function refreshAll() {
    await Promise.all([
      queryClient.invalidateQueries({ queryKey: ['worker-my-orders'] }),
      queryClient.invalidateQueries({ queryKey: ['worker-my-orders-overview'] }),
      queryClient.invalidateQueries({ queryKey: ['worker-cancel-requests'] }),
      queryClient.invalidateQueries({ queryKey: ['worker-order-feedbacks'] }),
    ])
  }

  function markOrderAsRead(order: WorkOrder) {
    if (order.isUnread) {
      queryClient.setQueriesData({ queryKey: ['worker-my-orders'] }, (current: unknown) =>
        patchWorkOrderReadState(current, order.workOrderId),
      )
    }
    // 每次打开详情都刷新资料查看时间，用于清除"资料已更新"角标。
    void markWorkerOrderRead(order.workOrderId, { materialSeen: true })
      .then(() => {
        void queryClient.invalidateQueries({ queryKey: ['worker-my-orders'] })
      })
      .catch(() => {
        void queryClient.invalidateQueries({ queryKey: ['worker-my-orders'] })
      })
  }

  function openOrderDetail(order: WorkOrder) {
    markOrderAsRead(order)
    setDetailOrder(order)
  }

  function copyOrderInfo(order: WorkOrder) {
    markOrderAsRead(order)
    const items = getCopyOrderInfoItems(order)
    if (items.length === 0) {
      message.warning('该订单暂无可复制信息')
      return
    }
    const text = items.map((item) => `${item.label}: ${item.value}`).join('\n')
    navigator.clipboard
      .writeText(text)
      .then(() => message.success('订单信息已复制'))
      .catch(() => message.error('复制失败，请手动复制'))
  }

  async function copyMaterialImages(order: WorkOrder) {
    const screenshots = getMaterialScreenshots(order)
    if (screenshots.length === 0) {
      message.warning('该订单暂无买家主页截图')
      return
    }
    if (typeof ClipboardItem === 'undefined') {
      message.error('当前浏览器不支持一键复制图片，请手动下载后发送')
      return
    }
    try {
      const blobs = await Promise.all(
        screenshots.map(async (file) => {
          const url = file.mediumUrl || file.url
          const response = await fetch(url)
          if (!response.ok) throw new Error(`图片加载失败 ${response.status}`)
          // Chrome 剪贴板写入仅支持 image/png，统一转成 PNG
          return toPngBlob(await response.blob())
        }),
      )
      const items = blobs.map((blob) => new ClipboardItem({ 'image/png': blob }))
      await navigator.clipboard.write(items)
      message.success(`已复制 ${blobs.length} 张图片，可直接粘贴发送`)
    } catch (error) {
      message.error(error instanceof Error ? error.message : '复制图片失败，请手动下载')
    }
  }

  function openAcceptanceModal(order: WorkOrder) {
    markOrderAsRead(order)
    setEditingOrder(order)
    if (canSupplementAcceptedEvidence(order)) {
      // 已验收补图只上传新增文件，原有验收图片由服务端保留。
      setAcceptanceFiles([])
      form.resetFields()
      setDetailOrder(null)
      return
    }
    // 已提交：以已提交的验收资料为初始内容；未提交：以暂存草稿为初始内容
    const source = hasSubmittedAcceptance(order)
      ? getWorkerAcceptance(order)
      : getWorkerDraft(order)
    setAcceptanceFiles(getUniqueAcceptanceFiles(source))
    form.setFieldsValue({ note: String(source?.note || '') })
    setDetailOrder(null)
  }

  function openGiftMaterialModal(order: WorkOrder) {
    markOrderAsRead(order)
    setGiftMaterialOrder(order)
    setGiftMaterialFiles([])
    giftMaterialForm.resetFields()
    setDetailOrder(null)
  }

  async function submitGiftMaterial(values: GiftMaterialFormValues) {
    if (!giftMaterialOrder) return
    if (giftMaterialFiles.length === 0) {
      message.error('请上传主页截图')
      return
    }
    const fields: Record<string, string> = {
      gameNickname: String(values.gameNickname || '').trim(),
      gameId: String(values.gameId || '').trim(),
      serverZone: String(values.serverZone || '').trim(),
    }
    const system = String(values.system || '').trim()
    if (system) fields.system = system
    try {
      await submitWorkerGiftMaterial(giftMaterialOrder.workOrderId, {
        fields,
        screenshots: giftMaterialFiles,
        note: String(values.note || '').trim(),
      })
      message.success('资料已提交，等待后台确认加好友')
      setGiftMaterialOrder(null)
      setGiftMaterialFiles([])
      giftMaterialForm.resetFields()
      await refreshAll()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '提交资料失败')
    }
  }

  function openNoteModal(order: WorkOrder) {
    markOrderAsRead(order)
    setNoteOrder(order)
    noteForm.setFieldsValue({ note: String(order.workerNote || '') })
  }

  function openCancelRequestModal(order: WorkOrder) {
    markOrderAsRead(order)
    setCancelRequestOrder(order)
    cancelRequestForm.resetFields()
  }

  async function submitCancelRequest(values: CancelRequestFormValues) {
    if (!cancelRequestOrder) return
    try {
      await submitWorkerCancelRequest(cancelRequestOrder.workOrderId, {
        reason: String(values.reason || '').trim(),
      })
      message.success('取消申请已提交，等待客服审核')
      setCancelRequestOrder(null)
      cancelRequestForm.resetFields()
      await refreshAll()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '提交取消申请失败')
    }
  }

  function openFeedbackModal(order: WorkOrder) {
    markOrderAsRead(order)
    setFeedbackOrder(order)
    feedbackForm.resetFields()
  }

  async function submitFeedback(values: FeedbackFormValues) {
    if (!feedbackOrder) return
    try {
      await submitWorkerOrderFeedback(feedbackOrder.workOrderId, {
        content: String(values.content || '').trim(),
      })
      message.success('问题反馈已提交，等待客服处理')
      setFeedbackOrder(null)
      feedbackForm.resetFields()
      await refreshAll()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '提交问题反馈失败')
    }
  }

  async function saveOrderNote(values: WorkerNoteFormValues) {
    if (!noteOrder) return
    try {
      await saveWorkerOrderNote(noteOrder.workOrderId, String(values.note || '').trim())
      message.success('备注已保存')
      setNoteOrder(null)
      noteForm.resetFields()
      await refreshAll()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '保存备注失败')
    }
  }

  async function submitAcceptanceReminder(order: WorkOrder) {
    try {
      await remindWorkerAcceptance(order.workOrderId)
      message.success('已催促管理员验收')
      await refreshAll()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '催验收失败')
    }
  }

  async function submitAcceptance(values: AcceptanceFormValues) {
    if (!editingOrder) return
    const isAcceptedEvidenceSupplement = canSupplementAcceptedEvidence(editingOrder)
    if (isAcceptedEvidenceSupplement) {
      if (acceptanceFiles.length === 0) {
        message.error('请上传新的验收图片')
        return
      }
      try {
        await supplementWorkerAcceptedOrderEvidence(editingOrder.workOrderId, {
          files: acceptanceFiles,
        })
        message.success('验收图片已补充')
        setEditingOrder(null)
        setAcceptanceFiles([])
        form.resetFields()
        await refreshAll()
      } catch (error) {
        message.error(error instanceof Error ? error.message : '补充验收图片失败')
      }
      return
    }

    if (isGiftSubmissionBlocked(editingOrder)) {
      message.error('好友赠送冷却未结束，暂不能提交验收')
      return
    }

    const canAutoAccept = canAutoAcceptOrder(editingOrder, workerCanAutoAcceptWithoutEvidence)
    if (acceptanceFiles.length === 0 && !canAutoAccept) {
      message.error('请上传验收图片')
      return
    }
    try {
      await submitWorkerAcceptance(editingOrder.workOrderId, {
        note: values.note,
        files: acceptanceFiles,
      })
      message.success(canAutoAccept ? '已自动验收，可在 24 小时内补充图片' : '已提交验收')
      setEditingOrder(null)
      setAcceptanceFiles([])
      form.resetFields()
      await refreshAll()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '提交失败')
    }
  }

  async function saveAcceptanceImages(values: AcceptanceFormValues) {
    if (!editingOrder) return
    if (hasSubmittedAcceptance(editingOrder) && acceptanceFiles.length === 0) {
      message.error('请至少保留一张验收图片')
      return
    }
    try {
      await saveWorkerAcceptanceDraft(editingOrder.workOrderId, {
        note: values.note,
        files: acceptanceFiles,
      })
      message.success(
        hasSubmittedAcceptance(editingOrder) ? '验收图片已更新' : '验收图片已暂存，可继续补充',
      )
      setEditingOrder(null)
      setAcceptanceFiles([])
      form.resetFields()
      await refreshAll()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '保存失败')
    }
  }

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

  const columns = buildWorkerOrderTableColumns({
    onOpenDetail: openOrderDetail,
    onOpenAcceptance: openAcceptanceModal,
    onOpenGiftMaterial: openGiftMaterialModal,
    onRemindAcceptance: (order) => {
      void submitAcceptanceReminder(order)
    },
    onOpenCancelRequest: openCancelRequestModal,
    onOpenFeedback: openFeedbackModal,
    onOpenNote: openNoteModal,
    onCopyOrderInfo: copyOrderInfo,
    onCopyMaterialImages: (order) => {
      void copyMaterialImages(order)
    },
  })

  return (
    <>
      <Button
        type="text"
        block={false}
        className="worker-after-sales-entry"
        onClick={() => navigate('/orders/after-sales')}
        style={{ padding: 0 }}
      >
        <Space
          style={{
            width: '100%',
            justifyContent: 'space-between',
            alignItems: 'center',
            background: '#fff',
            border: '1px solid #f0f0f0',
            borderRadius: 8,
            padding: '10px 14px',
            marginBottom: 12,
          }}
        >
          <Space size={8}>
            <Typography.Text strong>售后问题单</Typography.Text>
            <Typography.Text type="secondary" style={{ fontSize: 12 }}>
              验收后如被投诉，可在此查看与说明
            </Typography.Text>
          </Space>
          {afterSalesPendingCount > 0 ? (
            <Badge count={afterSalesPendingCount} color="orange" showZero={false} />
          ) : (
            <Typography.Text type="secondary">进入 &gt;</Typography.Text>
          )}
        </Space>
      </Button>
      {isMobile ? (
        <WorkerOrderMobileList
          statusOptions={STATUS_OPTIONS}
          status={status}
          overviewByStatus={overviewByStatus}
          keywordInput={keywordInput}
          keyword={keyword}
          orders={orders}
          pagination={pagination}
          page={page}
          pageSize={pageSize}
          loading={ordersQuery.isLoading}
          searching={ordersQuery.isFetching}
          refreshing={ordersQuery.isFetching || overviewQuery.isFetching}
          error={ordersQuery.error}
          onStatusChange={(nextStatus) => {
            setStatus(nextStatus)
            setPage(1)
          }}
          onKeywordInputChange={(nextValue) => {
            setKeywordInput(nextValue)
            if (!nextValue.trim()) {
              setKeyword('')
              setPage(1)
            }
          }}
          onKeywordSearch={applyKeywordSearch}
          onRefresh={() => {
            void refreshAll()
          }}
          onPageChange={(nextPage, nextPageSize) => {
            setPage(nextPage)
            setPageSize(nextPageSize)
          }}
          onOpenDetail={openOrderDetail}
          onOpenAcceptance={openAcceptanceModal}
          onOpenGiftMaterial={openGiftMaterialModal}
          onRemindAcceptance={(order) => {
            void submitAcceptanceReminder(order)
          }}
          onOpenCancelRequest={openCancelRequestModal}
          onOpenFeedback={openFeedbackModal}
          onOpenNote={openNoteModal}
          onCopyOrderInfo={copyOrderInfo}
          onCopyMaterialImages={(order) => {
            void copyMaterialImages(order)
          }}
        />
      ) : (
        <WorkerOrderDesktopList
          statusOptions={STATUS_OPTIONS}
          status={status}
          overviewByStatus={overviewByStatus}
          keywordInput={keywordInput}
          keyword={keyword}
          orders={orders}
          pagination={pagination}
          page={page}
          pageSize={pageSize}
          columns={columns}
          loading={ordersQuery.isLoading}
          searching={ordersQuery.isFetching}
          refreshing={ordersQuery.isFetching || overviewQuery.isFetching}
          error={ordersQuery.error}
          onRefresh={() => {
            void refreshAll()
          }}
          onStatusChange={(nextStatus) => {
            setStatus(nextStatus)
            setPage(1)
          }}
          onKeywordInputChange={(nextValue) => {
            setKeywordInput(nextValue)
            if (!nextValue.trim()) {
              setKeyword('')
              setPage(1)
            }
          }}
          onKeywordSearch={applyKeywordSearch}
          onPageChange={(nextPage, nextPageSize) => {
            setPage(nextPage)
            setPageSize(nextPageSize)
          }}
        />
      )}

      <WorkerOrderDetailDrawer
        isMobile={isMobile}
        order={detailOrder}
        orderTimelineVisible={orderTimelineVisible}
        onClose={() => setDetailOrder(null)}
        onOpenAcceptance={openAcceptanceModal}
        onOpenGiftMaterial={openGiftMaterialModal}
        onOpenCancelRequest={openCancelRequestModal}
        onOpenFeedback={openFeedbackModal}
      />
      <WorkerOrderModals
        isMobile={isMobile}
        feedbackOrder={feedbackOrder}
        feedbacks={feedbacksQuery.data?.data.items || []}
        feedbackForm={feedbackForm}
        onCloseFeedback={() => {
          setFeedbackOrder(null)
          feedbackForm.resetFields()
        }}
        onSubmitFeedback={submitFeedback}
        cancelRequestOrder={cancelRequestOrder}
        cancelRequestRisk={cancelRequestsQuery.data?.data.risk}
        cancelRequestForm={cancelRequestForm}
        onCloseCancelRequest={() => {
          setCancelRequestOrder(null)
          cancelRequestForm.resetFields()
        }}
        onSubmitCancelRequest={submitCancelRequest}
        noteOrder={noteOrder}
        noteForm={noteForm}
        onCloseNote={() => {
          setNoteOrder(null)
          noteForm.resetFields()
        }}
        onSaveNote={saveOrderNote}
        editingOrder={editingOrder}
        acceptanceFiles={acceptanceFiles}
        acceptanceForm={form}
        workerCanAutoAcceptWithoutEvidence={workerCanAutoAcceptWithoutEvidence}
        onCloseAcceptance={() => {
          setEditingOrder(null)
          setAcceptanceFiles([])
          form.resetFields()
        }}
        onAcceptanceFilesChange={setAcceptanceFiles}
        onSubmitAcceptance={submitAcceptance}
        onSaveAcceptanceImages={saveAcceptanceImages}
        giftMaterialOrder={giftMaterialOrder}
        giftMaterialForm={giftMaterialForm}
        giftMaterialFiles={giftMaterialFiles}
        onCloseGiftMaterial={() => {
          setGiftMaterialOrder(null)
          setGiftMaterialFiles([])
          giftMaterialForm.resetFields()
        }}
        onGiftMaterialFilesChange={setGiftMaterialFiles}
        onSubmitGiftMaterial={submitGiftMaterial}
      />
    </>
  )
}
