import { SearchOutlined, ReloadOutlined } from '@ant-design/icons'
import { Button, Card, Form, Input, Select, Space, Table, Typography } from 'antd'
import type { TableColumnsType } from 'antd'
import { useQuery } from '@tanstack/react-query'
import { useEffect, useMemo } from 'react'
import { useNavigate, useSearchParams } from 'react-router'

import { AdminRangePicker } from '@/components/admin/AdminDatePicker'
import PageHeader from '@/components/admin/PageHeader'
import StatusTag from '@/components/admin/StatusTag'
import dayjs from '@/lib/dayjs'
import { fetchAdminOrders } from '@/services/admin'
import type { AdminOrderListItem } from '@/types/admin'
import {
  adminOrderExecutorOptions,
  adminPayStatusOptions,
  adminTaskStatusOptions,
} from '@/utils/admin-options'
import {
  ADMIN_DEFAULT_PAGE_SIZE,
  buildAdminTablePagination,
  resolveAdminPageSize,
} from '@/utils/admin-pagination'
import { formatAdminDateTime } from '@/utils/admin-time'

type OrderFilterForm = {
  keyword?: string
  executorKey?: string
  payStatus?: string
  taskStatus?: string
  dateRange?: unknown
}

export default function AdminOrdersPage() {
  const navigate = useNavigate()
  const [form] = Form.useForm<OrderFilterForm>()
  const [searchParams, setSearchParams] = useSearchParams()
  const page = Number(searchParams.get('page') || 1) || 1
  const pageSize = resolveAdminPageSize(searchParams.get('pageSize'), ADMIN_DEFAULT_PAGE_SIZE)
  const filters = {
    keyword: searchParams.get('keyword') || '',
    executorKey: searchParams.get('executorKey') || '',
    payStatus: searchParams.get('payStatus') || '',
    taskStatus: searchParams.get('taskStatus') || '',
    dateFrom: searchParams.get('dateFrom') || '',
    dateTo: searchParams.get('dateTo') || '',
  }

  const queryParams = useMemo(
    () => ({ page, pageSize, ...filters }),
    [
      filters.dateFrom,
      filters.dateTo,
      filters.executorKey,
      filters.keyword,
      filters.payStatus,
      filters.taskStatus,
      page,
      pageSize,
    ],
  )
  const query = useQuery({
    queryKey: ['admin-orders', queryParams],
    queryFn: () => fetchAdminOrders(queryParams),
  })
  const data = query.data?.data

  useEffect(() => {
    form.setFieldsValue({
      keyword: filters.keyword || undefined,
      executorKey: filters.executorKey || undefined,
      payStatus: filters.payStatus || undefined,
      taskStatus: filters.taskStatus || undefined,
      dateRange:
        filters.dateFrom && filters.dateTo
          ? [dayjs(filters.dateFrom), dayjs(filters.dateTo)]
          : undefined,
    })
  }, [
    filters.dateFrom,
    filters.dateTo,
    filters.executorKey,
    filters.keyword,
    filters.payStatus,
    filters.taskStatus,
    form,
  ])

  const columns: TableColumnsType<AdminOrderListItem> = [
    {
      title: '订单信息',
      dataIndex: 'platformOrderId',
      minWidth: 220,
      render: (_, row) => (
        <div className="cell-stack">
          <Typography.Link onClick={() => navigate(`/admin/orders/${row.orderId}`)}>
            {row.platformOrderId}
          </Typography.Link>
          <span className="muted">{row.shopName || row.shopId || row.provider}</span>
        </div>
      ),
    },
    {
      title: '商品 / 任务',
      minWidth: 220,
      render: (_, row) => (
        <div className="cell-stack">
          <span>{row.itemSummary || '-'}</span>
          <span className="muted">
            商品 {row.itemCount} · 数量 {row.totalQuantity} · 任务 {row.taskCount}
          </span>
        </div>
      ),
    },
    {
      title: '状态',
      minWidth: 220,
      render: (_, row) => (
        <Space size={[0, 6]} wrap>
          <StatusTag value={row.payStatus} kind="pay" />
          <StatusTag value={row.resourceStatus} kind="resource" />
          <StatusTag value={row.customerStatus} kind="customer" />
        </Space>
      ),
    },
    {
      title: '金额 / 时间',
      minWidth: 180,
      render: (_, row) => (
        <div className="cell-stack">
          <strong>
            {row.totalAmount || '0.00'} {row.currency}
          </strong>
          <span className="muted">{formatAdminDateTime(row.createdAt)}</span>
        </div>
      ),
    },
  ]

  function applyFilters(values: OrderFilterForm) {
    const { dateRange, ...restValues } = values
    const [dateFrom, dateTo] = Array.isArray(dateRange)
      ? dateRange.map((item: { format?: (pattern: string) => string }) =>
          item?.format ? item.format('YYYY-MM-DD') : '',
        )
      : ['', '']

    setSearchParams(cleanParams({ ...restValues, dateFrom, dateTo, page: 1, pageSize }))
  }

  function resetFilters() {
    form.setFieldsValue({
      keyword: undefined,
      executorKey: undefined,
      payStatus: undefined,
      taskStatus: undefined,
      dateRange: undefined,
    })
    setSearchParams(cleanParams({ page: 1, pageSize }))
  }

  return (
    <section className="page-stack">
      <PageHeader title="订单" description="查看订单入库、商品匹配和任务拆分情况。" />

      <Card>
        <Form<OrderFilterForm>
          form={form}
          layout="inline"
          onFinish={applyFilters}
          className="filter-form"
        >
          <Form.Item name="keyword">
            <Input
              allowClear
              placeholder="订单号 / 商品标题 / SKU 标题 / 买家 / 店铺"
              style={{ width: 320 }}
            />
          </Form.Item>
          <Form.Item name="executorKey">
            <Select
              allowClear
              placeholder="履约渠道"
              options={adminOrderExecutorOptions}
              style={{ minWidth: 150 }}
            />
          </Form.Item>
          <Form.Item name="payStatus">
            <Select
              allowClear
              placeholder="支付状态"
              options={adminPayStatusOptions}
              style={{ minWidth: 140 }}
            />
          </Form.Item>
          <Form.Item name="taskStatus">
            <Select
              allowClear
              showSearch
              optionFilterProp="label"
              placeholder="任务状态"
              options={adminTaskStatusOptions}
              style={{ minWidth: 170 }}
            />
          </Form.Item>
          <Form.Item name="dateRange">
            <AdminRangePicker />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
                查询
              </Button>
              <Button icon={<ReloadOutlined />} onClick={resetFilters}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      <Card>
        <Table<AdminOrderListItem>
          rowKey="orderId"
          loading={query.isLoading || query.isFetching}
          columns={columns}
          dataSource={data?.items || []}
          scroll={{ x: 900 }}
          pagination={buildAdminTablePagination({
            current: data?.pagination.page || page,
            pageSize: data?.pagination.pageSize || pageSize,
            total: data?.pagination.total || 0,
            onChange: (nextPage, nextPageSize) => {
              setSearchParams(cleanParams({ ...filters, page: nextPage, pageSize: nextPageSize }))
            },
          })}
        />
      </Card>
    </section>
  )
}

function cleanParams(params: Record<string, unknown>) {
  const next = new URLSearchParams()
  Object.entries(params).forEach(([key, value]) => {
    const normalized = String(value ?? '').trim()
    if (normalized) {
      next.set(key, normalized)
    }
  })
  return next
}
