import { ArrowLeftOutlined } from '@ant-design/icons'
import { Alert, Button, Card, Descriptions, Skeleton, Space, Table, Typography } from 'antd'
import type { TableColumnsType } from 'antd'
import { useQuery } from '@tanstack/react-query'
import { useNavigate, useParams } from 'react-router'

import JsonPreview from '@/components/admin/JsonPreview'
import PageHeader from '@/components/admin/PageHeader'
import StatusTag from '@/components/admin/StatusTag'
import { fetchAdminOrderDetail } from '@/services/admin'
import type { AdminOrderDetail, AdminTaskListItem } from '@/types/admin'
import { formatAdminDateTime } from '@/utils/admin-time'

export default function AdminOrderDetailPage() {
  const navigate = useNavigate()
  const { orderId = '' } = useParams()
  const query = useQuery({
    queryKey: ['admin-order-detail', orderId],
    queryFn: () => fetchAdminOrderDetail(orderId),
    enabled: Boolean(orderId),
  })
  const detail = query.data?.data

  if (query.isLoading) {
    return (
      <section className="page-stack">
        <PageHeader title="订单详情" extra={<BackButton />} />
        <Card>
          <Skeleton active paragraph={{ rows: 10 }} />
        </Card>
      </section>
    )
  }

  if (query.error || !detail) {
    return (
      <section className="page-stack">
        <PageHeader title="订单详情" extra={<BackButton />} />
        <Alert
          type="error"
          showIcon
          message={query.error instanceof Error ? query.error.message : '订单不存在或读取失败'}
        />
      </section>
    )
  }

  const taskColumns: TableColumnsType<AdminTaskListItem> = [
    {
      title: '任务号',
      dataIndex: 'taskNo',
      minWidth: 180,
      render: (_, row) => (
        <Typography.Link onClick={() => navigate(`/admin/tasks/${row.taskId}`)}>
          {row.taskNo}
        </Typography.Link>
      ),
    },
    {
      title: '状态',
      minWidth: 220,
      render: (_, row) => (
        <Space size={[0, 6]} wrap>
          <StatusTag value={row.status} kind="task" />
          <StatusTag value={row.resourceStatus} kind="resource" />
          <StatusTag value={row.customerStatus} kind="customer" />
        </Space>
      ),
    },
    {
      title: '角色',
      minWidth: 160,
      render: (_, row) => (
        <div className="cell-stack">
          <span>{row.roleName || '-'}</span>
          <span className="muted">{row.roleId || '-'}</span>
        </div>
      ),
    },
    {
      title: '错误',
      dataIndex: 'lastError',
      minWidth: 220,
      render: (value) => <span className="muted">{value || '-'}</span>,
    },
  ]

  return (
    <section className="page-stack">
      <PageHeader
        title="订单详情"
        description={detail.order.platformOrderId}
        extra={<BackButton />}
      />

      <Card title="基础信息">
        <Descriptions column={{ xs: 1, md: 2, xl: 3 }} bordered size="small">
          <Descriptions.Item label="订单 ID">{detail.order.orderId}</Descriptions.Item>
          <Descriptions.Item label="店铺">
            {detail.order.shopName || detail.order.shopId || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="平台订单号">{detail.order.platformOrderId}</Descriptions.Item>
          <Descriptions.Item label="订单状态">
            <StatusTag value={detail.order.orderStatus} />
          </Descriptions.Item>
          <Descriptions.Item label="支付状态">
            <StatusTag value={detail.order.payStatus} kind="pay" />
          </Descriptions.Item>
          <Descriptions.Item label="金额">
            {detail.order.totalAmount} {detail.order.currency}
          </Descriptions.Item>
          <Descriptions.Item label="创建时间">
            {formatAdminDateTime(detail.order.createdAt)}
          </Descriptions.Item>
          <Descriptions.Item label="更新时间">
            {formatAdminDateTime(detail.order.updatedAt)}
          </Descriptions.Item>
          <Descriptions.Item label="商品摘要">{detail.order.itemSummary || '-'}</Descriptions.Item>
        </Descriptions>
      </Card>

      <Card title="商品明细">
        <Table<AdminOrderDetail['items'][number]>
          rowKey="orderItemId"
          pagination={false}
          dataSource={detail.items}
          scroll={{ x: 760 }}
          columns={[
            { title: '商品', dataIndex: 'itemTitle', minWidth: 240 },
            { title: 'SKU', dataIndex: 'skuCode', minWidth: 180 },
            { title: '数量', dataIndex: 'quantity', width: 90 },
            { title: '履约模式', dataIndex: 'deliveryMode', minWidth: 140 },
          ]}
        />
      </Card>

      <Card title="任务">
        <Table<AdminTaskListItem>
          rowKey="taskId"
          pagination={false}
          dataSource={detail.tasks}
          columns={taskColumns}
          scroll={{ x: 900 }}
        />
      </Card>

      <Card title="原始载荷">
        <JsonPreview value={detail.order.rawPayload} />
      </Card>
    </section>
  )
}

function BackButton() {
  const navigate = useNavigate()
  return (
    <Button icon={<ArrowLeftOutlined />} onClick={() => navigate('/admin/orders')}>
      返回订单
    </Button>
  )
}
