import {
  CheckOutlined,
  EyeOutlined,
  ReloadOutlined,
  SearchOutlined,
} from '@ant-design/icons'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import {
  App,
  Button,
  Card,
  Descriptions,
  Drawer,
  Empty,
  Form,
  Input,
  Modal,
  Space,
  Table,
  Tabs,
  Tag,
  Typography,
} from 'antd'
import type { TableColumnsType } from 'antd'
import { useEffect, useState } from 'react'

import { DeadlineCountdown } from '@/components/DeadlineCountdown'
import ImagePreviewList from '@/components/files/ImagePreviewList'
import ImageUpload from '@/components/files/ImageUpload'
import {
  cancelWorkerOrder,
  fetchWorkerMyOrders,
  submitWorkerAcceptance,
} from '@/services/worker'
import type { CollectField, UploadedFile, WorkOrder } from '@/types/worker-platform'
import { formatDateTime } from '@/utils/date-time'

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

type AcceptanceFormValues = {
  note?: string
}

type DetailFieldItem = {
  key: string
  label: string
  required: boolean
  value: string
}

export default function WorkerOrdersPage() {
  const { message, modal } = App.useApp()
  const queryClient = useQueryClient()
  const [status, setStatus] = useState('')
  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 [submittingOrder, setSubmittingOrder] = useState<WorkOrder | null>(null)
  const [acceptanceFiles, setAcceptanceFiles] = useState<UploadedFile[]>([])
  const [form] = Form.useForm<AcceptanceFormValues>()

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

  const overviewQuery = useQuery({
    queryKey: ['worker-my-orders-overview'],
    queryFn: async () => {
      const results = await Promise.all(
        STATUS_OPTIONS.map(async (item) => {
          const response = await fetchWorkerMyOrders({
            status: item.value,
            page: 1,
            pageSize: 1,
          })
          return [item.value || 'all', response.data.pagination.total] as const
        }),
      )
      return Object.fromEntries(results) as Record<string, number>
    },
    retry: false,
  })

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

  function openAcceptanceModal(order: WorkOrder) {
    setSubmittingOrder(order)
    setAcceptanceFiles([])
    form.resetFields()
    setDetailOrder(null)
  }

  async function submitAcceptance(values: AcceptanceFormValues) {
    if (!submittingOrder) return
    if (acceptanceFiles.length === 0) {
      message.error('请上传验收图片')
      return
    }
    try {
      await submitWorkerAcceptance(submittingOrder.workOrderId, {
        note: values.note,
        files: acceptanceFiles,
      })
      message.success('已提交验收')
      setSubmittingOrder(null)
      setAcceptanceFiles([])
      form.resetFields()
      await refreshAll()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '提交失败')
    }
  }

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

  function openCancelModal(order: WorkOrder) {
    modal.confirm({
      title: '确认取消接单？',
      content:
        '取消后订单将重新回到抢单大厅，冻结押金全额退还。30 天内取消次数有限，请谨慎操作。',
      okText: '确认取消',
      cancelText: '再想想',
      okButtonProps: { danger: true },
      onOk: async () => {
        try {
          await cancelWorkerOrder(order.workOrderId)
          message.success('已取消接单，押金已退还')
          await refreshAll()
        } catch (error) {
          message.error(error instanceof Error ? error.message : '取消接单失败')
        }
      },
    })
  }

  const columns: TableColumnsType<WorkOrder> = [
    {
      title: '订单信息',
      minWidth: 280,
      render: (_, row) => (
        <div className="cell-stack">
          <Typography.Link onClick={() => setDetailOrder(row)}>
            {row.productName || row.workOrderNo}
          </Typography.Link>
          <Space size={[6, 6]} wrap>
            {row.categoryName ? <Tag>{row.categoryName}</Tag> : null}
            {row.myShare ? <Tag color="purple">拼单</Tag> : null}
          </Space>
          <Typography.Text type="secondary">
            {row.workOrderNo} · {row.platformOrderId || '-'}
          </Typography.Text>
          <Typography.Text type="secondary">
            接单时间：{formatDateTime(row.assignedAt)}
          </Typography.Text>
        </div>
      ),
    },
    {
      title: '状态',
      width: 170,
      render: (_, row) => (
        <div className="cell-stack">
          <Space wrap size={6}>
            <Tag color={resolveStatusColor(row.status)}>{formatStatus(row.status)}</Tag>
            {row.status === 'in_progress' && row.deadlineAt ? (
              <DeadlineCountdown deadlineAt={row.deadlineAt} />
            ) : null}
          </Space>
          {row.status === 'problem' && String(row.problemNote || '').trim() ? (
            <Typography.Text type="danger" ellipsis>
              {row.problemNote}
            </Typography.Text>
          ) : null}
        </div>
      ),
    },
    {
      title: '奖励 / 押金',
      width: 150,
      render: (_, row) => (
        <div className="cell-stack">
          <Typography.Text strong>{formatMoney(row.rewardAmount)}</Typography.Text>
          <Typography.Text type="secondary">
            冻结押金：{formatMoney(row.freezeDepositAmount)}
          </Typography.Text>
          {row.myShare ? (
            <Typography.Text type="secondary">
              {row.myShare.quantity} 份 · 份额 {formatMoney(row.myShare.shareReward)}
            </Typography.Text>
          ) : null}
        </div>
      ),
    },
    {
      title: '验收信息',
      minWidth: 200,
      render: (_, row) => {
        const submittedAt = getAcceptanceSubmittedAt(row)
        const hasAcceptance =
          getAcceptanceFiles(row).length > 0 || getAcceptanceImageUrls(row).length > 0
        if (!hasAcceptance && !submittedAt) {
          return <Typography.Text type="secondary">未提交</Typography.Text>
        }
        return (
          <div className="cell-stack">
            <ImagePreviewList
              files={getAcceptanceFiles(row)}
              imageUrls={getAcceptanceImageUrls(row)}
              size={40}
            />
            <Typography.Text type="secondary">
              提交时间：{formatDateTime(submittedAt)}
            </Typography.Text>
            {row.acceptance?.note ? (
              <Typography.Text type="secondary" ellipsis>
                {row.acceptance.note}
              </Typography.Text>
            ) : null}
          </div>
        )
      },
    },
    {
      title: '操作',
      width: 260,
      render: (_, row) => (
        <Space wrap>
          <Button icon={<EyeOutlined />} onClick={() => setDetailOrder(row)}>
            详情
          </Button>
          {canSubmitAcceptance(row) ? (
            <Button
              icon={<CheckOutlined />}
              type="primary"
              onClick={() => openAcceptanceModal(row)}
            >
              提交验收
            </Button>
          ) : null}
          {canCancelOrder(row) ? (
            <Button danger onClick={() => openCancelModal(row)}>
              取消接单
            </Button>
          ) : null}
        </Space>
      ),
    },
  ]

  return (
    <section className="page-stack">
      <div className="worker-page-head">
        <Typography.Title level={3}>我的订单</Typography.Title>
        <Button
          icon={<ReloadOutlined />}
          loading={ordersQuery.isFetching || overviewQuery.isFetching}
          onClick={() => refreshAll()}
        >
          刷新
        </Button>
      </div>

      <Card bordered={false}>
        <Space direction="vertical" size={16} style={{ width: '100%' }}>
          <Tabs
            activeKey={status || 'all'}
            items={STATUS_OPTIONS.map((item) => {
              const countKey = item.value || 'all'
              const count = Number(overviewQuery.data?.[countKey] || 0)
              return {
                key: item.value || 'all',
                label: (
                  <span>
                    {item.label}
                    {count > 0 ? (
                      <span className="worker-order-tab-count">{count}</span>
                    ) : null}
                  </span>
                ),
              }
            })}
            onChange={(nextKey) => {
              const nextStatus = nextKey === 'all' ? '' : nextKey
              setStatus(nextStatus)
              setPage(1)
            }}
          />

          <Space.Compact style={{ width: '100%', maxWidth: 460 }}>
            <Input
              allowClear
              value={keywordInput}
              placeholder="搜索工单号 / 订单号 / 商品名"
              prefix={<SearchOutlined />}
              onChange={(event) => {
                const nextValue = event.target.value
                setKeywordInput(nextValue)
                if (!nextValue.trim()) {
                  setKeyword('')
                  setPage(1)
                }
              }}
              onPressEnter={applyKeywordSearch}
            />
            <Button
              icon={<SearchOutlined />}
              loading={ordersQuery.isFetching}
              onClick={applyKeywordSearch}
            >
              搜索
            </Button>
          </Space.Compact>

          <Table<WorkOrder>
            rowKey="workOrderId"
            size="small"
            loading={ordersQuery.isLoading}
            dataSource={orders}
            columns={columns}
            locale={{
              emptyText: ordersQuery.error ? (
                <Empty
                  description={
                    ordersQuery.error instanceof Error
                      ? ordersQuery.error.message
                      : '读取我的订单失败'
                  }
                />
              ) : (
                <Empty
                  description={
                    keyword
                      ? `没有找到与 “${keyword}” 相关的订单`
                      : '当前筛选下暂无订单'
                  }
                />
              ),
            }}
            pagination={{
              current: pagination?.page || page,
              pageSize: pagination?.pageSize || pageSize,
              total: pagination?.total || 0,
              showSizeChanger: true,
              pageSizeOptions: [10, 20, 50, 100],
              showTotal: (total) => `共 ${total} 条`,
              onChange: (nextPage, nextPageSize) => {
                setPage(nextPage)
                setPageSize(nextPageSize)
              },
            }}
            scroll={{ x: 1060 }}
          />
        </Space>
      </Card>

      <Drawer
        title={
          detailOrder
            ? `${detailOrder.productName || '订单详情'} · ${detailOrder.workOrderNo}`
            : '订单详情'
        }
        width={820}
        open={Boolean(detailOrder)}
        destroyOnHidden
        onClose={() => setDetailOrder(null)}
        extra={
          detailOrder ? (
            <Space>
              <Tag color={resolveStatusColor(detailOrder.status)}>
                {formatStatus(detailOrder.status)}
              </Tag>
              {canCancelOrder(detailOrder) ? (
                <Button danger onClick={() => openCancelModal(detailOrder)}>
                  取消接单
                </Button>
              ) : null}
              {canSubmitAcceptance(detailOrder) ? (
                <Button
                  type="primary"
                  icon={<CheckOutlined />}
                  onClick={() => openAcceptanceModal(detailOrder)}
                >
                  提交验收
                </Button>
              ) : null}
            </Space>
          ) : null
        }
      >
        {detailOrder ? (
          <div className="worker-order-detail-stack">
            <Card title="基础信息" size="small">
              <Descriptions column={{ xs: 1, md: 2 }} bordered size="small">
                <Descriptions.Item label="商品">
                  {detailOrder.productName || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="分类">
                  {detailOrder.categoryName || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="工单号">
                  {detailOrder.workOrderNo}
                </Descriptions.Item>
                <Descriptions.Item label="平台订单号">
                  {detailOrder.platformOrderId || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="状态">
                  <Tag color={resolveStatusColor(detailOrder.status)}>
                    {formatStatus(detailOrder.status)}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="阶段说明">
                  {getStatusHint(detailOrder.status)}
                </Descriptions.Item>
                <Descriptions.Item label="接单奖励">
                  {formatMoney(detailOrder.rewardAmount)}
                </Descriptions.Item>
                <Descriptions.Item label="冻结押金">
                  {formatMoney(detailOrder.freezeDepositAmount)}
                </Descriptions.Item>
                <Descriptions.Item label="接单时间">
                  {formatDateTime(detailOrder.assignedAt)}
                </Descriptions.Item>
                <Descriptions.Item label="提交验收">
                  {formatDateTime(getAcceptanceSubmittedAt(detailOrder))}
                </Descriptions.Item>
                <Descriptions.Item label="验收完成">
                  {formatDateTime(detailOrder.acceptedAt)}
                </Descriptions.Item>
                <Descriptions.Item label="更新时间">
                  {formatDateTime(detailOrder.updatedAt)}
                </Descriptions.Item>
              </Descriptions>
            </Card>

            <Card title="资料信息" size="small">
              {renderDetailFieldValues(
                getMaterialDetailItems(detailOrder),
                '当前还没有资料内容',
              )}
            </Card>

            <Card title="资料要求" size="small">
              {renderRequirementFieldValues(detailOrder)}
            </Card>

            <Card title="验收信息" size="small">
              <div className="worker-order-detail-stack">
                <Descriptions column={{ xs: 1, md: 2 }} bordered size="small">
                  <Descriptions.Item label="验收图片数量">
                    {getAcceptanceFiles(detailOrder).length +
                      getAcceptanceImageUrls(detailOrder).length || 0}
                  </Descriptions.Item>
                  <Descriptions.Item label="提交时间">
                    {formatDateTime(getAcceptanceSubmittedAt(detailOrder))}
                  </Descriptions.Item>
                  <Descriptions.Item label="验收说明" span={2}>
                    <span className="worker-order-detail-value">
                      {String(detailOrder.acceptance?.note || '').trim() || '-'}
                    </span>
                  </Descriptions.Item>
                </Descriptions>
                {getAcceptanceFiles(detailOrder).length ||
                getAcceptanceImageUrls(detailOrder).length ? (
                  <ImagePreviewList
                    files={getAcceptanceFiles(detailOrder)}
                    imageUrls={getAcceptanceImageUrls(detailOrder)}
                    size={76}
                  />
                ) : (
                  <Typography.Text type="secondary">暂无验收图片</Typography.Text>
                )}
              </div>
            </Card>

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

      <Modal
        title="提交验收"
        open={Boolean(submittingOrder)}
        onCancel={() => {
          setSubmittingOrder(null)
          setAcceptanceFiles([])
          form.resetFields()
        }}
        onOk={() => form.submit()}
        destroyOnHidden
      >
        <Form form={form} layout="vertical" onFinish={submitAcceptance}>
          <Form.Item label="完成说明" name="note">
            <Input.TextArea
              rows={3}
              placeholder="可补充代练结果、注意事项或截图说明。"
            />
          </Form.Item>
          <Form.Item label="验收图片" required>
            <ImageUpload
              scene="worker-acceptance"
              scope="worker"
              value={acceptanceFiles}
              onChange={setAcceptanceFiles}
              maxCount={6}
              showPasteHint
            />
          </Form.Item>
        </Form>
      </Modal>
    </section>
  )
}

function canSubmitAcceptance(order: WorkOrder) {
  if (order.myShare) {
    return order.myShare.status === 'joined' && order.status !== 'accepted'
  }
  return ['in_progress', 'problem'].includes(order.status)
}

function canCancelOrder(order: WorkOrder) {
  return !order.myShare && order.status === 'in_progress'
}

function getRequirementFields(order: WorkOrder | null): CollectField[] {
  if (!order) return []
  const rawFields = Array.isArray(order.requirement?.fields)
    ? order.requirement.fields
    : []
  return rawFields
    .map((item) => {
      const source = asRecord(item)
      const key = String(source.key || '').trim()
      if (!key) return null
      return {
        key,
        label: String(source.label || key).trim(),
        required: source.required !== false,
      }
    })
    .filter((item): item is CollectField => Boolean(item))
}

function getMaterialFields(order: WorkOrder): Record<string, string> {
  const material = asRecord(order.material)
  const collect = asRecord(material.collect)
  const fields = asRecord(collect.fields || material.fields)
  return Object.fromEntries(
    Object.entries(fields).map(([key, value]) => [key, String(value || '')]),
  )
}

function getMaterialDetailItems(order: WorkOrder): DetailFieldItem[] {
  const values = getMaterialFields(order)
  const requiredFields = getRequirementFields(order)
  const usedKeys = new Set<string>()
  const items = requiredFields.map((field) => {
    usedKeys.add(field.key)
    return {
      key: field.key,
      label: field.label,
      required: field.required,
      value: String(values[field.key] || ''),
    }
  })

  Object.entries(values).forEach(([key, value]) => {
    if (usedKeys.has(key)) return
    items.push({
      key,
      label: key,
      required: false,
      value: String(value || ''),
    })
  })

  return items
}

function renderDetailFieldValues(items: DetailFieldItem[], emptyText: string) {
  if (items.length === 0) {
    return <Typography.Text type="secondary">{emptyText}</Typography.Text>
  }

  return (
    <Descriptions column={1} bordered size="small">
      {items.map((item) => (
        <Descriptions.Item
          key={item.key}
          label={
            <Space size={6} wrap>
              <span>{item.label}</span>
              {item.required ? <Tag color="orange">必填</Tag> : null}
            </Space>
          }
        >
          <span className="worker-order-detail-value">
            {String(item.value || '').trim() || '-'}
          </span>
        </Descriptions.Item>
      ))}
    </Descriptions>
  )
}

function renderRequirementFieldValues(order: WorkOrder) {
  const fields = getRequirementFields(order)
  if (fields.length === 0) {
    return <Typography.Text type="secondary">当前工单未配置资料要求</Typography.Text>
  }

  return (
    <Descriptions column={1} bordered size="small">
      {fields.map((field) => (
        <Descriptions.Item key={field.key} label={field.label}>
          <Space size={6} wrap>
            <Typography.Text code>{field.key}</Typography.Text>
            <Tag color={field.required ? 'orange' : 'default'}>
              {field.required ? '必填' : '选填'}
            </Tag>
          </Space>
        </Descriptions.Item>
      ))}
    </Descriptions>
  )
}

function getAcceptanceFiles(row: WorkOrder): UploadedFile[] {
  return Array.isArray(row.acceptance?.files) ? row.acceptance.files : []
}

function getAcceptanceImageUrls(row: WorkOrder): string[] {
  return Array.isArray(row.acceptance?.imageUrls)
    ? row.acceptance.imageUrls
        .map((item) => String(item || '').trim())
        .filter(Boolean)
    : []
}

function getAcceptanceSubmittedAt(order: WorkOrder): string | null {
  const acceptanceSubmittedAt =
    typeof order.acceptance?.submittedAt === 'string'
      ? order.acceptance.submittedAt
      : null
  return order.submittedAt || acceptanceSubmittedAt || null
}

function asRecord(value: unknown): Record<string, unknown> {
  return value && typeof value === 'object' && !Array.isArray(value)
    ? (value as Record<string, unknown>)
    : {}
}

function formatMoney(value: number | undefined) {
  return `￥${((Number(value || 0) || 0) / 100).toFixed(2)}`
}

function formatStatus(status: string) {
  const labels: Record<string, string> = {
    open: '已超时',
    in_progress: '代练中',
    pending_acceptance: '待验收',
    problem: '问题单',
    accepted: '已验收',
    cancelled: '已取消',
  }
  return labels[status] || status
}

function getStatusHint(status: string) {
  const hints: Record<string, string> = {
    open: '任务已超时被系统判定失败，如需继续可前往大厅重新抢单。',
    in_progress: '订单进行中，完成后请及时提交验收资料。',
    pending_acceptance: '已提交验收，等待后台审核。',
    problem: '后台已标记问题，请根据备注调整后重新提交。',
    accepted: '订单已完成验收，可以在个人中心查看结算记录。',
    cancelled: '订单已取消，本次流程已结束。',
  }
  return hints[status] || '请关注当前订单状态变化。'
}

function resolveStatusColor(status: string) {
  if (status === 'accepted') return 'green'
  if (status === 'cancelled') return 'default'
  if (status === 'problem') return 'red'
  if (status === 'pending_acceptance') return 'gold'
  if (status === 'open') return 'red'
  return 'blue'
}
