import { MessageOutlined, PictureOutlined, UserAddOutlined } from '@ant-design/icons'
import { Button, Card, Descriptions, Drawer, Space, Steps, Tag, Typography } from 'antd'

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

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

export function WorkerOrderDetailDrawer({
  isMobile,
  order,
  orderTimelineVisible,
  onClose,
  onOpenAcceptance,
  onOpenGiftMaterial,
  onOpenCancelRequest,
  onOpenFeedback,
}: {
  isMobile: boolean
  order: WorkOrder | null
  orderTimelineVisible: boolean
  onClose: () => void
  onOpenAcceptance: (order: WorkOrder) => void
  onOpenGiftMaterial: (order: WorkOrder) => void
  onOpenCancelRequest: (order: WorkOrder) => void
  onOpenFeedback: (order: WorkOrder) => void
}) {
  return (
    <Drawer
      className="worker-order-detail-drawer"
      title="订单详情"
      width={isMobile ? '100%' : 820}
      open={Boolean(order)}
      destroyOnHidden
      onClose={onClose}
    >
      {order ? (
        <div className="worker-order-detail-stack">
          <div className="worker-order-detail-actions">
            <Tag color={getOrderStatusDisplay(order).color}>
              {getOrderStatusDisplay(order).label}
            </Tag>
            {canSubmitGiftMaterial(order) ? (
              <Button
                type="primary"
                icon={<UserAddOutlined />}
                onClick={() => onOpenGiftMaterial(order)}
              >
                提交好友赠送资料
              </Button>
            ) : null}
            {canEditAcceptanceImages(order) ? (
              <Button
                type={canSubmitAcceptance(order) ? 'primary' : 'default'}
                icon={<PictureOutlined />}
                onClick={() => onOpenAcceptance(order)}
              >
                {hasSubmittedAcceptance(order) ? '补充图片' : '上传图片 / 提交验收'}
              </Button>
            ) : null}
            {canRequestCancel(order) ? (
              <Button danger onClick={() => onOpenCancelRequest(order)}>
                申请取消
              </Button>
            ) : null}
            {canSubmitFeedback(order) ? (
              <Button icon={<MessageOutlined />} onClick={() => onOpenFeedback(order)}>
                问题反馈
              </Button>
            ) : null}
          </div>
          <Card title="基础信息" size="small">
            <Descriptions column={{ xs: 1, md: 2 }} bordered size="small">
              <Descriptions.Item label="商品">{order.productName || '-'}</Descriptions.Item>
              <Descriptions.Item label="分类">{order.categoryName || '-'}</Descriptions.Item>
              <Descriptions.Item label="平台订单号">{getDisplayOrderNo(order)}</Descriptions.Item>
              <Descriptions.Item label="状态">
                <Tag color={getOrderStatusDisplay(order).color}>
                  {getOrderStatusDisplay(order).label}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="阶段说明">{getOrderStatusHint(order)}</Descriptions.Item>
              <Descriptions.Item label="接单奖励">
                {formatMoney(order.rewardAmount)}
              </Descriptions.Item>
              <Descriptions.Item label="冻结押金">
                {formatMoney(order.freezeDepositAmount)}
              </Descriptions.Item>
              <Descriptions.Item label="接单时间">
                {formatDateTime(order.assignedAt)}
              </Descriptions.Item>
              <Descriptions.Item label="提交验收">
                {formatDateTime(getAcceptanceSubmittedAt(order))}
              </Descriptions.Item>
              <Descriptions.Item label="验收完成">
                {formatDateTime(order.acceptedAt)}
              </Descriptions.Item>
              <Descriptions.Item label="更新时间">
                {formatDateTime(order.updatedAt)}
              </Descriptions.Item>
            </Descriptions>
          </Card>

          <Card title="资料信息" size="small">
            {renderDetailFieldValues(getMaterialDetailItems(order), '当前还没有资料内容')}
            {getMaterialScreenshots(order).length > 0 ? (
              <div style={{ marginTop: 12 }}>
                <Typography.Text type="secondary">买家主页截图</Typography.Text>
                <div style={{ marginTop: 8 }}>
                  <ImagePreviewList files={getMaterialScreenshots(order)} size={72} />
                </div>
              </div>
            ) : null}
          </Card>

          {isFriendGiftOrder(order) && order.gift ? <GiftProgressCard order={order} /> : null}

          <Card title="验收信息" size="small">
            <AcceptanceSummary order={order} />
          </Card>

          {String(order.problemNote || '').trim() ? (
            <Card title="问题备注" size="small">
              <span className="worker-order-detail-value">
                {String(order.problemNote || '').trim()}
              </span>
            </Card>
          ) : null}

          {orderTimelineVisible ? (
            <Card title="流转记录" size="small">
              <WorkOrderEventTimeline orderId={order.workOrderId} viewer="worker" />
            </Card>
          ) : null}
        </div>
      ) : null}
    </Drawer>
  )
}

function GiftProgressCard({ order }: { order: WorkOrder }) {
  const gift = order.gift
  if (!gift) return null
  const phaseMeta = getGiftPhaseMeta(gift.phase)
  const stepIndex =
    gift.phase === 'material_required'
      ? 0
      : gift.phase === 'material_submitted'
        ? 1
        : gift.phase === 'friend_countdown'
          ? 2
          : 3
  const boosterFields = gift.boosterMaterial?.fields || {}
  const boosterFieldLabels: Record<string, string> = {
    gameNickname: '游戏昵称',
    gameId: '游戏ID',
    serverZone: '区服',
    system: '系统',
  }
  const boosterItems = Object.entries(boosterFields).filter(([, value]) =>
    String(value || '').trim(),
  )

  return (
    <Card title="好友赠送进度" size="small">
      <div className="worker-order-detail-stack">
        <Space size={8} wrap>
          <Tag color={phaseMeta.color}>{phaseMeta.label}</Tag>
          {gift.phase === 'friend_countdown' ? (
            <GiftCountdownTag giftAvailableAt={gift.giftAvailableAt} />
          ) : null}
          {gift.phase === 'gift_ready' ? (
            <Tag color="green">可赠送，完成后请提交赠送凭证</Tag>
          ) : null}
        </Space>
        <Steps
          size="small"
          current={stepIndex}
          items={[
            { title: '提交资料' },
            { title: '添加好友' },
            { title: '冷却等待' },
            { title: '赠送交付' },
          ]}
        />
        <Descriptions column={{ xs: 1, md: 2 }} bordered size="small">
          <Descriptions.Item label="冷却时长">
            {gift.cooldownMinutes > 0
              ? `${gift.cooldownMinutes} 分钟`
              : `${gift.cooldownHours} 小时`}
          </Descriptions.Item>
          <Descriptions.Item label="已加好友">
            {formatDateTime(gift.friendAddedAt)}
          </Descriptions.Item>
          <Descriptions.Item label="可赠送时间" span={2}>
            {gift.giftAvailableAt ? (
              <Space size={8} wrap>
                <span>{formatDateTime(gift.giftAvailableAt)}</span>
                {gift.phase === 'friend_countdown' ? (
                  <GiftCountdownTag giftAvailableAt={gift.giftAvailableAt} />
                ) : null}
              </Space>
            ) : (
              '-'
            )}
          </Descriptions.Item>
        </Descriptions>
        {boosterItems.length > 0 || (gift.boosterMaterial?.screenshots || []).length > 0 ? (
          <div>
            <Typography.Text type="secondary">已提交的本人资料</Typography.Text>
            <div style={{ marginTop: 8 }}>
              {boosterItems.length > 0 ? (
                <Descriptions column={{ xs: 1, md: 2 }} bordered size="small">
                  {boosterItems.map(([key, value]) => (
                    <Descriptions.Item key={key} label={boosterFieldLabels[key] || key}>
                      <span className="worker-order-detail-value">{String(value)}</span>
                    </Descriptions.Item>
                  ))}
                </Descriptions>
              ) : null}
              {(gift.boosterMaterial?.screenshots || []).length > 0 ? (
                <div style={{ marginTop: 8 }}>
                  <ImagePreviewList files={gift.boosterMaterial.screenshots} size={64} />
                </div>
              ) : null}
            </div>
          </div>
        ) : (
          <Typography.Text type="secondary">尚未提交本人资料</Typography.Text>
        )}
      </div>
    </Card>
  )
}

function AcceptanceSummary({ order }: { order: WorkOrder }) {
  const acceptanceFiles = getUniqueAcceptanceFiles(getWorkerAcceptance(order))
  const draftFiles = getUniqueAcceptanceFiles(getWorkerDraft(order))
  const hasAcceptance = acceptanceFiles.length > 0
  const hasDraft = draftFiles.length > 0 && !hasSubmittedAcceptance(order)

  return (
    <div className="worker-order-detail-stack">
      <Descriptions column={{ xs: 1, md: 2 }} bordered size="small">
        <Descriptions.Item label="验收图片数量">{acceptanceFiles.length}</Descriptions.Item>
        <Descriptions.Item label="提交时间">
          {formatDateTime(getAcceptanceSubmittedAt(order))}
        </Descriptions.Item>
        <Descriptions.Item label="验收说明" span={2}>
          <span className="worker-order-detail-value">
            {String(getWorkerAcceptance(order)?.note || '').trim() || '-'}
          </span>
        </Descriptions.Item>
      </Descriptions>

      {hasAcceptance ? (
        <ImagePreviewList files={acceptanceFiles} size={76} />
      ) : (
        <Typography.Text type="secondary">暂无已提交验收图片</Typography.Text>
      )}

      {hasDraft ? (
        <div className="acceptance-draft-badge-wrap" style={{ marginTop: 8 }}>
          <Tag color="processing" icon={<PictureOutlined />}>
            已暂存 {draftFiles.length} 张图片（未提交，刷新不丢失）
          </Tag>
          <ImagePreviewList files={draftFiles} size={76} />
        </div>
      ) : null}
    </div>
  )
}
