import {
  CopyOutlined,
  EditOutlined,
  EyeOutlined,
  MessageOutlined,
  PictureOutlined,
  ReloadOutlined,
  SearchOutlined,
} from '@ant-design/icons'
import { Button, Empty, Input, Pagination, Spin, Tag } from 'antd'

import { DeadlineCountdown } from '@/components/DeadlineCountdown'
import ImagePreviewList from '@/components/files/ImagePreviewList'
import type {
  Pagination as PaginationData,
  WorkerOrderOverviewItem,
  WorkOrder,
} from '@/types/worker-platform'
import { formatDateTime } from '@/utils/date-time'

import type { WorkerOrderStatusOption } from './WorkerOrderDesktopList'
import {
  canEditAcceptanceImages,
  canRemindAcceptance,
  canRequestCancel,
  canSubmitAcceptance,
  canSubmitFeedback,
  canSubmitGiftMaterial,
  formatMoney,
  getCopyOrderInfoItems,
  getDisplayOrderNo,
  getMaterialDetailItems,
  getMaterialScreenshots,
  getOrderFlagTags,
  getOrderStatusDisplay,
  getSettlementLabel,
  getUniqueAcceptanceFiles,
  getWorkerAcceptance,
  getWorkerDraft,
  GiftCountdownTag,
  hasSubmittedAcceptance,
  isFriendGiftOrder,
  isVipEvidencePending,
} from './worker-order-utils'

export function WorkerOrderMobileList({
  statusOptions,
  status,
  overviewByStatus,
  keywordInput,
  keyword,
  orders,
  pagination,
  page,
  pageSize,
  loading,
  searching,
  refreshing,
  error,
  onStatusChange,
  onKeywordInputChange,
  onKeywordSearch,
  onRefresh,
  onPageChange,
  onOpenDetail,
  onOpenAcceptance,
  onOpenGiftMaterial,
  onRemindAcceptance,
  onOpenCancelRequest,
  onOpenFeedback,
  onOpenNote,
  onCopyOrderInfo,
  onCopyMaterialImages,
}: {
  statusOptions: readonly WorkerOrderStatusOption[]
  status: string
  overviewByStatus: Map<string, WorkerOrderOverviewItem>
  keywordInput: string
  keyword: string
  orders: WorkOrder[]
  pagination: PaginationData | undefined
  page: number
  pageSize: number
  loading: boolean
  searching: boolean
  refreshing: boolean
  error: unknown
  onStatusChange: (status: string) => void
  onKeywordInputChange: (keyword: string) => void
  onKeywordSearch: () => void
  onRefresh: () => void
  onPageChange: (page: number, pageSize: number) => void
  onOpenDetail: (order: WorkOrder) => void
  onOpenAcceptance: (order: WorkOrder) => void
  onOpenGiftMaterial: (order: WorkOrder) => void
  onRemindAcceptance: (order: WorkOrder) => void
  onOpenCancelRequest: (order: WorkOrder) => void
  onOpenFeedback: (order: WorkOrder) => void
  onOpenNote: (order: WorkOrder) => void
  onCopyOrderInfo: (order: WorkOrder) => void
  onCopyMaterialImages: (order: WorkOrder) => void
}) {
  return (
    <div className="worker-orders-mobile-page">
      <div className="worker-orders-mobile-status-bar">
        {statusOptions.map((item) => {
          const overview = overviewByStatus.get(item.value || 'all')
          const count = Number(overview?.orderCount || 0)
          return (
            <button
              key={item.value || 'all'}
              type="button"
              className={`worker-orders-status-pill ${(status || '') === item.value ? 'active' : ''}`}
              onClick={() => onStatusChange(item.value)}
            >
              <span className="worker-orders-status-pill-main">
                <span>{item.label}</span>
                {count > 0 ? (
                  <span className="worker-orders-status-pill-count">{count}</span>
                ) : null}
              </span>
              <span className="worker-orders-status-pill-settlement">
                {getSettlementLabel(item.value)} {formatMoney(overview?.settlementAmount)}
              </span>
            </button>
          )
        })}
      </div>

      <div className="worker-orders-mobile-search-row">
        <Input
          allowClear
          value={keywordInput}
          placeholder="搜索订单号 / 商品名 / 游戏ID / 游戏昵称"
          prefix={<SearchOutlined />}
          className="worker-orders-mobile-search-input"
          onChange={(event) => onKeywordInputChange(event.target.value)}
          onPressEnter={onKeywordSearch}
        />
        <Button
          type="primary"
          icon={<SearchOutlined />}
          loading={searching}
          onClick={onKeywordSearch}
        />
        <Button icon={<ReloadOutlined />} loading={refreshing} onClick={onRefresh} title="刷新" />
      </div>

      <div className="worker-orders-mobile-list">
        {loading ? (
          <div className="worker-hall-loading">
            <Spin size="large" />
          </div>
        ) : error ? (
          <Empty description={error instanceof Error ? error.message : '读取我的订单失败'} />
        ) : orders.length === 0 ? (
          <Empty
            description={keyword ? `没有找到与 “${keyword}” 相关的订单` : '当前筛选下暂无订单'}
          />
        ) : (
          orders.map((order) => (
            <WorkerOrderMobileCard
              key={order.workOrderId}
              order={order}
              onOpenDetail={onOpenDetail}
              onOpenAcceptance={onOpenAcceptance}
              onOpenGiftMaterial={onOpenGiftMaterial}
              onRemindAcceptance={onRemindAcceptance}
              onOpenCancelRequest={onOpenCancelRequest}
              onOpenFeedback={onOpenFeedback}
              onOpenNote={onOpenNote}
              onCopyOrderInfo={onCopyOrderInfo}
              onCopyMaterialImages={onCopyMaterialImages}
            />
          ))
        )}
        {(pagination?.total || 0) > 0 ? (
          <div className="worker-orders-mobile-pagination">
            <Pagination
              current={pagination?.page || page}
              pageSize={pagination?.pageSize || pageSize}
              total={pagination?.total || 0}
              simple
              onChange={onPageChange}
            />
          </div>
        ) : null}
      </div>
    </div>
  )
}

function WorkerOrderMobileCard({
  order,
  onOpenDetail,
  onOpenAcceptance,
  onOpenGiftMaterial,
  onRemindAcceptance,
  onOpenCancelRequest,
  onOpenFeedback,
  onOpenNote,
  onCopyOrderInfo,
  onCopyMaterialImages,
}: Omit<
  Parameters<typeof WorkerOrderMobileList>[0],
  | 'statusOptions'
  | 'status'
  | 'overviewByStatus'
  | 'keywordInput'
  | 'keyword'
  | 'orders'
  | 'pagination'
  | 'page'
  | 'pageSize'
  | 'loading'
  | 'searching'
  | 'refreshing'
  | 'error'
  | 'onStatusChange'
  | 'onKeywordInputChange'
  | 'onKeywordSearch'
  | 'onRefresh'
  | 'onPageChange'
> & { order: WorkOrder }) {
  const items = getMaterialDetailItems(order).filter((item) => String(item.value || '').trim())
  const screenshots = getMaterialScreenshots(order)
  const acceptanceFiles = getUniqueAcceptanceFiles(getWorkerAcceptance(order))
  const draftFiles = getUniqueAcceptanceFiles(getWorkerDraft(order))
  const noteText = getWorkerAcceptance(order)?.note
  const workerNote = String(order.workerNote || '').trim()
  const statusDisplay = getOrderStatusDisplay(order)
  const flagTags = getOrderFlagTags(order)

  return (
    <article className="worker-order-mobile-card">
      <div className="worker-order-mobile-header">
        <div className="worker-order-mobile-header-left">
          {order.isUnread ? (
            <Tag color="purple" className="worker-order-unread-tag">
              新
            </Tag>
          ) : null}
          {order.categoryName ? (
            <Tag color="blue" className="worker-order-mobile-tag">
              {order.categoryName}
            </Tag>
          ) : null}
          {order.myShare ? (
            <Tag color="purple" className="worker-order-mobile-tag">
              拼单
            </Tag>
          ) : null}
          {flagTags.map((flag) => (
            <Tag key={flag.key} color={flag.color} className="worker-order-mobile-tag">
              {flag.label}
            </Tag>
          ))}
          <span className="worker-order-mobile-orderno-text">{getDisplayOrderNo(order)}</span>
        </div>
        <div className="worker-order-mobile-header-right">
          <Tag color={statusDisplay.color}>{statusDisplay.label}</Tag>
          {order.status === 'in_progress' && order.deadlineAt ? (
            <DeadlineCountdown deadlineAt={order.deadlineAt} />
          ) : null}
          {isFriendGiftOrder(order) &&
          order.status === 'in_progress' &&
          order.gift?.phase === 'friend_countdown' ? (
            <GiftCountdownTag giftAvailableAt={order.gift.giftAvailableAt} />
          ) : null}
        </div>
      </div>

      <div className="worker-order-mobile-main-row">
        <div className="worker-order-mobile-product-title">{order.productName || '未命名商品'}</div>
        <div className="worker-order-mobile-price-badge">
          <span className="worker-order-mobile-price-label">报酬</span>
          <strong className="worker-order-mobile-price-num">
            {formatMoney(order.rewardAmount)}
          </strong>
        </div>
      </div>
      <div className="worker-order-mobile-sub-row">
        <span className="worker-order-mobile-sub-item">
          押金: {formatMoney(order.freezeDepositAmount)}
        </span>
        {order.myShare ? (
          <span className="worker-order-mobile-sub-item">
            已拼 {order.myShare.quantity} 份 ({formatMoney(order.myShare.shareReward)})
          </span>
        ) : null}
        <span className="worker-order-mobile-sub-time">{formatDateTime(order.assignedAt)}</span>
      </div>

      {order.status === 'problem' && String(order.problemNote || '').trim() ? (
        <div className="worker-order-mobile-problem-box">
          <strong>问题：</strong>
          <span>{order.problemNote}</span>
        </div>
      ) : null}
      {items.length > 0 || screenshots.length > 0 ? (
        <div className="worker-order-mobile-credentials-box">
          {items.length > 0 ? (
            <div className="worker-order-mobile-credentials-grid">
              {items.map((item) => (
                <div key={item.key} className="worker-order-mobile-credential-line">
                  <span className="worker-order-mobile-credential-label">{item.label}:</span>
                  <span className="worker-order-mobile-credential-val">{item.value}</span>
                </div>
              ))}
            </div>
          ) : null}
          {screenshots.length > 0 ? (
            <div className="worker-order-mobile-screenshots-row">
              <span className="worker-order-mobile-credential-label">截图:</span>
              <ImagePreviewList files={screenshots} size={34} />
            </div>
          ) : null}
          <div className="worker-order-mobile-copy-toolbar">
            <Button
              size="small"
              icon={<CopyOutlined />}
              disabled={getCopyOrderInfoItems(order).length === 0}
              onClick={() => onCopyOrderInfo(order)}
            >
              复制资料
            </Button>
            {screenshots.length > 0 ? (
              <Button
                size="small"
                icon={<PictureOutlined />}
                onClick={() => onCopyMaterialImages(order)}
              >
                复制图片
              </Button>
            ) : null}
          </div>
        </div>
      ) : null}

      {acceptanceFiles.length > 0 ||
      (draftFiles.length > 0 && !hasSubmittedAcceptance(order)) ||
      noteText ? (
        <div className="worker-order-mobile-acceptance-strip">
          {acceptanceFiles.length > 0 ? (
            <div className="worker-order-mobile-acceptance-files">
              <span className="worker-order-mobile-acceptance-tag">
                已提交凭据 ({acceptanceFiles.length}张)
              </span>
              <ImagePreviewList files={acceptanceFiles} size={32} maxVisible={3} />
            </div>
          ) : null}
          {isVipEvidencePending(order) ? <Tag color="purple">VIP 免审核，待补图</Tag> : null}
          {draftFiles.length > 0 && !hasSubmittedAcceptance(order) ? (
            <div className="worker-order-mobile-draft-files">
              <Tag color="processing" icon={<PictureOutlined />}>
                已暂存 {draftFiles.length} 张图片
              </Tag>
              <ImagePreviewList files={draftFiles} size={32} maxVisible={3} />
            </div>
          ) : null}
          {noteText ? (
            <div className="worker-order-mobile-acceptance-text">说明：{noteText}</div>
          ) : null}
        </div>
      ) : null}

      <div className="worker-order-mobile-footer-row">
        <div className="worker-order-mobile-note-block">
          {workerNote ? (
            <div
              className={`worker-note-badge theme-${resolveNoteTheme(workerNote)}`}
              onClick={() => onOpenNote(order)}
            >
              <span className="worker-note-text" title={workerNote}>
                {workerNote}
              </span>
              <EditOutlined className="worker-note-edit-icon" />
            </div>
          ) : (
            <button
              type="button"
              className="worker-order-mobile-add-note-btn"
              onClick={() => onOpenNote(order)}
            >
              <EditOutlined /> 添加备注
            </button>
          )}
        </div>
        <div className="worker-order-mobile-btn-group">
          <Button size="small" icon={<EyeOutlined />} onClick={() => onOpenDetail(order)}>
            详情
          </Button>
          {canSubmitGiftMaterial(order) ? (
            <Button
              size="small"
              type="primary"
              className="worker-order-mobile-action-submit"
              onClick={() => onOpenGiftMaterial(order)}
            >
              提交资料
            </Button>
          ) : null}
          {canEditAcceptanceImages(order) ? (
            <Button
              size="small"
              type={canSubmitAcceptance(order) ? 'primary' : 'default'}
              icon={<PictureOutlined />}
              className="worker-order-mobile-action-submit"
              onClick={() => onOpenAcceptance(order)}
            >
              {hasSubmittedAcceptance(order) ? '补充图片' : '提交验收'}
            </Button>
          ) : null}
          {canRemindAcceptance(order) ? (
            <Button size="small" onClick={() => onRemindAcceptance(order)}>
              催验收
            </Button>
          ) : null}
          {canRequestCancel(order) ? (
            <Button size="small" danger onClick={() => onOpenCancelRequest(order)}>
              申请取消
            </Button>
          ) : null}
          {canSubmitFeedback(order) ? (
            <Button size="small" icon={<MessageOutlined />} onClick={() => onOpenFeedback(order)}>
              反馈
            </Button>
          ) : null}
        </div>
      </div>
    </article>
  )
}

function resolveNoteTheme(note?: string) {
  const text = String(note || '')
    .trim()
    .toLowerCase()
  if (!text) return 'default'
  if (
    ['问题', '异常', '密码', '封号', '错误', '无法', '投诉', '退', '失败', '被挤'].some((item) =>
      text.includes(item),
    )
  )
    return 'danger'
  if (
    ['未安排', '未', '暂缓', '暂停', '稍后', '延后', '挂起', '待定'].some((item) =>
      text.includes(item),
    )
  )
    return 'warning'
  if (['排队', '等待', '等买家', '等扫码', '等验证', '待扫'].some((item) => text.includes(item)))
    return 'purple'
  if (
    ['打单', '做单', '进行', '处理', '上号', '练级', '正在', '开打', '肝'].some((item) =>
      text.includes(item),
    )
  )
    return 'processing'
  if (
    ['已安排', '安排', '已就绪', '就绪', '已联系', '完成', '已好', '搞定', '正常', 'ok'].some(
      (item) => text.includes(item),
    )
  )
    return 'success'
  return 'default'
}
