import {
  CopyOutlined,
  EditOutlined,
  EyeOutlined,
  MessageOutlined,
  PictureOutlined,
} from '@ant-design/icons'
import { Button, Space, Tag, Tooltip, Typography } from 'antd'
import type { TableColumnsType } from 'antd'

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

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

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

export function buildWorkerOrderTableColumns({
  onOpenDetail,
  onOpenAcceptance,
  onOpenGiftMaterial,
  onRemindAcceptance,
  onOpenCancelRequest,
  onOpenFeedback,
  onOpenNote,
  onCopyOrderInfo,
  onCopyMaterialImages,
}: {
  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
}): TableColumnsType<WorkOrder> {
  return [
    {
      title: '订单信息',
      width: 270,
      render: (_, row) => (
        <div className="cell-stack">
          <Space size={4} align="center">
            {row.isUnread ? (
              <Tag color="purple" className="worker-order-unread-tag">
                新
              </Tag>
            ) : null}
            <Typography.Link
              strong
              onClick={() => onOpenDetail(row)}
              title={row.productName || '未命名商品'}
              ellipsis
            >
              {row.productName || '未命名商品'}
            </Typography.Link>
          </Space>
          <Space size={[4, 4]} wrap>
            {row.categoryName ? <Tag color="blue">{row.categoryName}</Tag> : null}
            {row.myShare ? <Tag color="purple">拼单</Tag> : null}
          </Space>
          <Typography.Text
            type="secondary"
            style={{ fontSize: 12 }}
            ellipsis={{ tooltip: getDisplayOrderNo(row) }}
          >
            {getDisplayOrderNo(row)}
          </Typography.Text>
          <Typography.Text type="secondary" style={{ fontSize: 12 }}>
            接单：{formatDateTime(row.assignedAt)}
          </Typography.Text>
        </div>
      ),
    },
    {
      title: '状态',
      width: 130,
      render: (_, row) => {
        const statusDisplay = getOrderStatusDisplay(row)
        const flagTags = getOrderFlagTags(row)
        return (
          <div className="cell-stack">
            <Space wrap size={4}>
              <Tag color={statusDisplay.color}>{statusDisplay.label}</Tag>
              {row.status === 'in_progress' && row.deadlineAt ? (
                <DeadlineCountdown deadlineAt={row.deadlineAt} />
              ) : null}
              {isFriendGiftOrder(row) &&
              row.status === 'in_progress' &&
              row.gift?.phase === 'friend_countdown' ? (
                <GiftCountdownTag giftAvailableAt={row.gift.giftAvailableAt} />
              ) : null}
            </Space>
            {flagTags.length > 0 ? (
              <Space wrap size={4}>
                {flagTags.map((flag) => (
                  <Tag key={flag.key} color={flag.color}>
                    {flag.label}
                  </Tag>
                ))}
              </Space>
            ) : null}
            {row.status === 'problem' && String(row.problemNote || '').trim() ? (
              <Typography.Text
                type="danger"
                ellipsis={{ tooltip: row.problemNote }}
                style={{ fontSize: 12 }}
              >
                {row.problemNote}
              </Typography.Text>
            ) : null}
          </div>
        )
      },
    },
    {
      title: '奖励 / 押金',
      width: 140,
      render: (_, row) => (
        <div className="cell-stack">
          <Typography.Text strong style={{ color: '#cf1322' }}>
            {formatMoney(row.rewardAmount)}
          </Typography.Text>
          <Typography.Text type="secondary" style={{ fontSize: 12 }}>
            押金：{formatMoney(row.freezeDepositAmount)}
          </Typography.Text>
          {row.myShare ? (
            <Typography.Text type="secondary" style={{ fontSize: 12 }}>
              {row.myShare.quantity} 份 · {formatMoney(row.myShare.shareReward)}
            </Typography.Text>
          ) : null}
        </div>
      ),
    },
    {
      title: '验收信息',
      width: 220,
      render: (_, row) => <AcceptanceCell order={row} />,
    },
    {
      title: '快捷复制',
      width: 250,
      render: (_, row) => {
        const items = getMaterialDetailItems(row).filter((item) => String(item.value || '').trim())
        const screenshots = getMaterialScreenshots(row)
        return (
          <div className="cell-stack">
            {items.length > 0 ? (
              items.map((item) => (
                <Typography.Text
                  key={item.key}
                  style={{ fontSize: 12 }}
                  ellipsis={{ tooltip: `${item.label}: ${item.value}` }}
                >
                  {item.label}: {item.value}
                </Typography.Text>
              ))
            ) : (
              <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                暂无资料信息
              </Typography.Text>
            )}
            {screenshots.length > 0 ? <ImagePreviewList files={screenshots} size={34} /> : null}
            <Space wrap size={4}>
              <Button
                size="small"
                icon={<CopyOutlined />}
                disabled={getCopyOrderInfoItems(row).length === 0}
                onClick={() => onCopyOrderInfo(row)}
              >
                复制信息
              </Button>
              {screenshots.length > 0 ? (
                <Button
                  size="small"
                  icon={<PictureOutlined />}
                  onClick={() => onCopyMaterialImages(row)}
                >
                  复制图片
                </Button>
              ) : null}
            </Space>
          </div>
        )
      },
    },
    {
      title: '备注',
      width: 180,
      render: (_, row) => <NoteCell order={row} onOpenNote={onOpenNote} />,
    },
    {
      title: '操作',
      width: 150,
      render: (_, row) => (
        <div className="worker-order-actions">
          <Space size={6}>
            <Tooltip title="查看详情">
              <Button
                aria-label="查看详情"
                icon={<EyeOutlined />}
                onClick={() => onOpenDetail(row)}
              />
            </Tooltip>
            {canSubmitGiftMaterial(row) ? (
              <Button type="primary" onClick={() => onOpenGiftMaterial(row)}>
                提交资料
              </Button>
            ) : null}
            {canEditAcceptanceImages(row) ? (
              <Button
                icon={<PictureOutlined />}
                type={canSubmitAcceptance(row) ? 'primary' : 'default'}
                onClick={() => onOpenAcceptance(row)}
              >
                {hasSubmittedAcceptance(row) ? '补充图片' : '验收'}
              </Button>
            ) : null}
            {canRemindAcceptance(row) ? (
              <Button onClick={() => onRemindAcceptance(row)}>催验收</Button>
            ) : null}
            {canRequestCancel(row) ? (
              <Button danger onClick={() => onOpenCancelRequest(row)}>
                申请取消
              </Button>
            ) : null}
            {canSubmitFeedback(row) ? (
              <Tooltip title="反馈客户资料或订单处理问题">
                <Button icon={<MessageOutlined />} onClick={() => onOpenFeedback(row)}>
                  反馈
                </Button>
              </Tooltip>
            ) : null}
          </Space>
        </div>
      ),
    },
  ]
}

function AcceptanceCell({ order }: { order: WorkOrder }) {
  const submittedAt = getAcceptanceSubmittedAt(order)
  const acceptanceFiles = getUniqueAcceptanceFiles(getWorkerAcceptance(order))
  const draftFiles = getUniqueAcceptanceFiles(getWorkerDraft(order))
  if (acceptanceFiles.length === 0 && !submittedAt && draftFiles.length === 0) {
    return (
      <Typography.Text type="secondary" style={{ fontSize: 12 }}>
        未提交
      </Typography.Text>
    )
  }
  return (
    <div className="cell-stack">
      {acceptanceFiles.length > 0 ? (
        <ImagePreviewList files={acceptanceFiles} size={38} maxVisible={2} />
      ) : null}
      {submittedAt ? (
        <Typography.Text type="secondary" style={{ fontSize: 12 }}>
          提交：{formatDateTime(submittedAt)}
        </Typography.Text>
      ) : null}
      {isVipEvidencePending(order) ? <Tag color="purple">VIP 免审核，待补图</Tag> : null}
      {draftFiles.length > 0 && !hasSubmittedAcceptance(order) ? (
        <div className="acceptance-draft-badge-wrap">
          <Tag color="processing" icon={<PictureOutlined />}>
            已暂存 {draftFiles.length} 张图片
          </Tag>
          <ImagePreviewList files={draftFiles} size={38} maxVisible={2} />
        </div>
      ) : null}
      {getWorkerAcceptance(order)?.note ? (
        <Typography.Text
          type="secondary"
          ellipsis={{ tooltip: getWorkerAcceptance(order)?.note }}
          style={{ fontSize: 12 }}
        >
          {getWorkerAcceptance(order)?.note}
        </Typography.Text>
      ) : null}
    </div>
  )
}

function NoteCell({
  order,
  onOpenNote,
}: {
  order: WorkOrder
  onOpenNote: (order: WorkOrder) => void
}) {
  const note = String(order.workerNote || '').trim()
  return (
    <div className="worker-note-cell">
      {note ? (
        <div
          className={`worker-note-badge theme-${resolveNoteTheme(note)}`}
          onClick={() => onOpenNote(order)}
        >
          <span className="worker-note-text" title={note}>
            {note}
          </span>
          <EditOutlined className="worker-note-edit-icon" />
        </div>
      ) : (
        <Button
          type="dashed"
          size="small"
          icon={<EditOutlined />}
          className="worker-note-add-btn"
          onClick={() => onOpenNote(order)}
        >
          添加备注
        </Button>
      )}
    </div>
  )
}

function resolveNoteTheme(note?: string): NoteTheme {
  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'
}
