import { useMemo, useState, type ReactNode } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import {
  CalendarClock,
  CheckCircle2,
  Clock,
  Eye,
  FileSearch,
  KeyRound,
  Loader2,
  MoreHorizontal,
  PauseCircle,
  Play,
  RefreshCcw,
  Repeat,
  RotateCcw,
  SearchIcon,
  SquarePen,
  WalletCards,
  XCircle,
  Zap,
} from 'lucide-react'
import { toast } from 'sonner'
import { getApiErrorMessage } from '@/lib/api'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
} from '@/components/ui/sheet'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { Textarea } from '@/components/ui/textarea'
import { AdminPage } from '@/features/admin/components/admin-page'
import { ListPagination } from '@/features/admin/components/list-pagination'
import { formatDateTime } from '@/features/admin/utils'
import {
  getOrderDetail,
  listOrders,
  markOrderPaid,
  refreshThirdPartyOrder,
  runLocalOrderAction,
  runThirdPartyOrderAction,
  type FulfillmentStatus,
  type LocalOrderAction,
  type OrderAction,
  type OrderDetail,
  type OrderFulfillment,
  type OrderItem,
  type PaymentStatus,
  type ThirdPartyOrderAction,
  type ThirdPartyOrderActionPayload,
} from './api'

const FILTER_ALL = 'all'

const paymentStatusLabels: Record<PaymentStatus, string> = {
  unpaid: '待支付',
  paying: '支付中',
  paid: '已支付',
  pay_failed: '支付失败',
  closed: '已关闭',
  refunding: '退款中',
  refunded: '已退款',
  partial_refunded: '部分退款',
}

const fulfillmentStatusLabels: Record<FulfillmentStatus, string> = {
  pending: '待履约',
  submitting: '提交中',
  submitted: '已提交',
  processing: '处理中',
  completed: '已完成',
  failed: '履约失败',
  canceled: '已取消',
}

const thirdPartyActionLabels: Record<ThirdPartyOrderAction | 'refresh', string> =
  {
    refresh: '查单刷新',
    budan: '补单',
    gaimi: '改密',
    stop: '暂停',
    priority: '优先学习',
    convert: '课程转换',
    'update-time': '修改时长',
    'update-cycle': '修改周期',
  }

const localActionLabels: Record<LocalOrderAction, string> = {
  process: '开始处理',
  complete: '完成发货',
  cancel: '取消履约',
  close: '关闭订单',
  remark: '更新备注',
}

type ThirdPartyDialogState = {
  order: OrderDetail
  action: ThirdPartyOrderAction | 'refresh'
}

type LocalDialogState = {
  order: OrderDetail
  action: LocalOrderAction
}

type ThirdPartyActionForm = {
  externalOrderNo: string
  username: string
  newPwd: string
  remark: string
  city: string
  tag: string
  config: string
  autoReset: string
  convertToClassId: string
  time: string
  cycle: string
}

const defaultThirdPartyForm: ThirdPartyActionForm = {
  externalOrderNo: '',
  username: '',
  newPwd: '',
  remark: '',
  city: '',
  tag: '',
  config: '',
  autoReset: '0',
  convertToClassId: '',
  time: '',
  cycle: '',
}

function formatPrice(value: string) {
  const numberValue = Number(value)
  return Number.isFinite(numberValue) ? `¥${numberValue.toFixed(2)}` : value
}

function sourceLabel(sourceType: OrderDetail['sourceType']) {
  return sourceType === 'third_party' ? '第三方' : '自营'
}

function paymentVariant(status: PaymentStatus) {
  if (status === 'paid') return 'default'
  if (status === 'pay_failed' || status === 'closed') return 'destructive'
  return 'secondary'
}

function fulfillmentVariant(status: FulfillmentStatus) {
  if (status === 'completed' || status === 'submitted') return 'default'
  if (status === 'failed' || status === 'canceled') return 'destructive'
  return 'outline'
}

function actionStatusVariant(status: OrderAction['status']) {
  return status === 'success' ? 'default' : 'destructive'
}

function getPrimaryFulfillment(order: OrderDetail) {
  return order.fulfillments?.[0] ?? null
}

function stringifyPayload(value: unknown) {
  if (value === undefined || value === null || value === '') return '-'
  if (typeof value === 'string') return value
  try {
    return JSON.stringify(value, null, 2)
  } catch {
    return String(value)
  }
}

export function OrdersPage() {
  const queryClient = useQueryClient()
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [keywordInput, setKeywordInput] = useState('')
  const [keyword, setKeyword] = useState('')
  const [sourceType, setSourceType] = useState(FILTER_ALL)
  const [paymentStatus, setPaymentStatus] = useState(FILTER_ALL)
  const [fulfillmentStatus, setFulfillmentStatus] = useState(FILTER_ALL)
  const [selectedOrder, setSelectedOrder] = useState<OrderDetail | null>(null)
  const [thirdPartyDialog, setThirdPartyDialog] =
    useState<ThirdPartyDialogState | null>(null)
  const [thirdPartyForm, setThirdPartyForm] =
    useState<ThirdPartyActionForm>(defaultThirdPartyForm)
  const [localDialog, setLocalDialog] = useState<LocalDialogState | null>(null)
  const [localRemark, setLocalRemark] = useState('')

  const ordersQuery = useQuery({
    queryKey: [
      'orders',
      page,
      pageSize,
      keyword,
      sourceType,
      paymentStatus,
      fulfillmentStatus,
    ],
    queryFn: () =>
      listOrders({
        page,
        pageSize,
        keyword,
        sourceType: sourceType === FILTER_ALL ? undefined : sourceType,
        paymentStatus:
          paymentStatus === FILTER_ALL ? undefined : paymentStatus,
        fulfillmentStatus:
          fulfillmentStatus === FILTER_ALL ? undefined : fulfillmentStatus,
      }),
  })

  const selectedOrderId = selectedOrder?.id
  const detailQuery = useQuery({
    queryKey: ['orders', 'detail', selectedOrderId],
    queryFn: () => getOrderDetail(selectedOrderId || ''),
    enabled: Boolean(selectedOrderId),
  })
  const activeOrder = detailQuery.data ?? selectedOrder

  const markPaidMutation = useMutation({
    mutationFn: markOrderPaid,
    onSuccess: (order) => {
      toast.success('已标记支付成功并触发履约')
      handleOrderUpdated(order)
    },
    onError: (error) =>
      toast.error(getApiErrorMessage(error, '标记支付失败')),
  })

  const thirdPartyMutation = useMutation({
    mutationFn: (input: {
      order: OrderDetail
      action: ThirdPartyOrderAction | 'refresh'
      payload: ThirdPartyOrderActionPayload
    }) =>
      input.action === 'refresh'
        ? refreshThirdPartyOrder(input.order.id, input.payload)
        : runThirdPartyOrderAction(
            input.order.id,
            input.action,
            input.payload
          ),
    onSuccess: (order) => {
      toast.success('第三方订单操作已完成')
      setThirdPartyDialog(null)
      handleOrderUpdated(order)
    },
    onError: (error) =>
      toast.error(getApiErrorMessage(error, '第三方订单操作失败')),
  })

  const syncThirdPartyDetailMutation = useMutation({
    mutationFn: (order: OrderDetail) => refreshThirdPartyOrder(order.id, {}),
    onSuccess: (order) => {
      toast.success('第三方订单详情已同步')
      queryClient.setQueryData(['orders', 'detail', order.id], order)
      if (selectedOrder?.id === order.id) {
        setSelectedOrder(order)
      }
      void queryClient.invalidateQueries({ queryKey: ['orders'] })
    },
    onError: (error) =>
      toast.error(getApiErrorMessage(error, '同步第三方订单失败')),
  })

  const localMutation = useMutation({
    mutationFn: (input: {
      order: OrderDetail
      action: LocalOrderAction
      remark: string
    }) =>
      runLocalOrderAction(input.order.id, input.action, {
        remark: input.remark || null,
      }),
    onSuccess: (order) => {
      toast.success('自营订单操作已完成')
      setLocalDialog(null)
      handleOrderUpdated(order)
    },
    onError: (error) =>
      toast.error(getApiErrorMessage(error, '自营订单操作失败')),
  })

  function handleOrderUpdated(order: OrderDetail) {
    setSelectedOrder(order)
    queryClient.setQueryData(['orders', 'detail', order.id], order)
    void queryClient.invalidateQueries({ queryKey: ['orders'] })
  }

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

  function handleReset() {
    setPage(1)
    setKeyword('')
    setKeywordInput('')
    setSourceType(FILTER_ALL)
    setPaymentStatus(FILTER_ALL)
    setFulfillmentStatus(FILTER_ALL)
  }

  function openThirdPartyDialog(
    order: OrderDetail,
    action: ThirdPartyOrderAction | 'refresh'
  ) {
    setThirdPartyDialog({ order, action })
    setThirdPartyForm(defaultThirdPartyForm)
  }

  function openLocalDialog(order: OrderDetail, action: LocalOrderAction) {
    setLocalDialog({ order, action })
    setLocalRemark(action === 'remark' ? order.remark || '' : '')
  }

  function handleThirdPartySubmit() {
    if (!thirdPartyDialog) return

    const payload = buildThirdPartyPayload(thirdPartyDialog.action)
    if (!payload) return

    thirdPartyMutation.mutate({
      order: thirdPartyDialog.order,
      action: thirdPartyDialog.action,
      payload,
    })
  }

  function buildThirdPartyPayload(
    action: ThirdPartyOrderAction | 'refresh'
  ): ThirdPartyOrderActionPayload | null {
    const payload: ThirdPartyOrderActionPayload = {
      externalOrderNo: thirdPartyForm.externalOrderNo.trim() || null,
    }
    if (action === 'refresh') {
      payload.username = thirdPartyForm.username.trim() || null
    }
    if (action === 'gaimi') {
      payload.newPwd = thirdPartyForm.newPwd.trim() || null
      payload.remark = thirdPartyForm.remark.trim() || null
      payload.city = thirdPartyForm.city.trim() || null
      payload.tag = thirdPartyForm.tag.trim() || null
      payload.autoReset = thirdPartyForm.autoReset
      if (thirdPartyForm.config.trim()) {
        try {
          payload.config = JSON.parse(thirdPartyForm.config)
        } catch {
          toast.error('动态配置需要填写合法 JSON')
          return null
        }
      }
    }
    if (action === 'convert') {
      payload.convertToClassId = thirdPartyForm.convertToClassId.trim()
    }
    if (action === 'update-time') {
      payload.time = thirdPartyForm.time.trim()
    }
    if (action === 'update-cycle') {
      payload.cycle = thirdPartyForm.cycle.trim()
    }
    return payload
  }

  const orders = ordersQuery.data?.list ?? []
  const isActionPending =
    markPaidMutation.isPending ||
    thirdPartyMutation.isPending ||
    syncThirdPartyDetailMutation.isPending ||
    localMutation.isPending

  return (
    <AdminPage
      title='订单列表'
      description='管理订单详情、第三方订单操作和自营订单本地履约。'
    >
      <div className='flex flex-col gap-4'>
        <div className='flex flex-wrap items-center gap-2'>
          <Input
            value={keywordInput}
            placeholder='搜索订单号或备注'
            className='h-9 w-64'
            onChange={(event) => setKeywordInput(event.target.value)}
            onKeyDown={(event) => {
              if (event.key === 'Enter') handleSearch()
            }}
          />
          <Select
            value={sourceType}
            onValueChange={(value) => {
              setPage(1)
              setSourceType(value)
            }}
          >
            <SelectTrigger className='h-9 w-32'>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value={FILTER_ALL}>全部来源</SelectItem>
              <SelectItem value='third_party'>第三方</SelectItem>
              <SelectItem value='self_owned'>自营</SelectItem>
            </SelectContent>
          </Select>
          <Select
            value={paymentStatus}
            onValueChange={(value) => {
              setPage(1)
              setPaymentStatus(value)
            }}
          >
            <SelectTrigger className='h-9 w-36'>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value={FILTER_ALL}>全部支付</SelectItem>
              {Object.entries(paymentStatusLabels).map(([value, label]) => (
                <SelectItem key={value} value={value}>
                  {label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Select
            value={fulfillmentStatus}
            onValueChange={(value) => {
              setPage(1)
              setFulfillmentStatus(value)
            }}
          >
            <SelectTrigger className='h-9 w-36'>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value={FILTER_ALL}>全部履约</SelectItem>
              {Object.entries(fulfillmentStatusLabels).map(([value, label]) => (
                <SelectItem key={value} value={value}>
                  {label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Button variant='outline' onClick={handleSearch}>
            <SearchIcon />
            查询
          </Button>
          <Button variant='ghost' onClick={handleReset}>
            <RotateCcw />
            重置
          </Button>
        </div>

        <div className='overflow-auto rounded-md border'>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>订单号</TableHead>
                <TableHead>商品</TableHead>
                <TableHead>来源</TableHead>
                <TableHead>金额</TableHead>
                <TableHead>支付</TableHead>
                <TableHead>履约</TableHead>
                <TableHead>创建时间</TableHead>
                <TableHead className='w-40 text-right'>操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {ordersQuery.isLoading ? (
                <TableRow>
                  <TableCell colSpan={8} className='h-24 text-center'>
                    <Loader2 className='mx-auto animate-spin' />
                  </TableCell>
                </TableRow>
              ) : orders.length ? (
                orders.map((order) => (
                  <TableRow key={order.id}>
                    <TableCell className='font-medium'>
                      {order.orderNo}
                    </TableCell>
                    <TableCell>
                      {order.items?.[0]?.productName || '-'}
                    </TableCell>
                    <TableCell>{sourceLabel(order.sourceType)}</TableCell>
                    <TableCell>{formatPrice(order.payableAmount)}</TableCell>
                    <TableCell>
                      <Badge variant={paymentVariant(order.paymentStatus)}>
                        {paymentStatusLabels[order.paymentStatus]}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Badge
                        variant={fulfillmentVariant(order.fulfillmentStatus)}
                      >
                        {fulfillmentStatusLabels[order.fulfillmentStatus]}
                      </Badge>
                    </TableCell>
                    <TableCell>{formatDateTime(order.createdAt)}</TableCell>
                    <TableCell className='text-right'>
                      <div className='flex items-center justify-end gap-1'>
                        {order.sourceType === 'third_party' && (
                          <Button
                            size='sm'
                            variant='outline'
                            disabled={syncThirdPartyDetailMutation.isPending}
                            onClick={() =>
                              syncThirdPartyDetailMutation.mutate(order)
                            }
                          >
                            {syncThirdPartyDetailMutation.isPending &&
                            syncThirdPartyDetailMutation.variables?.id ===
                              order.id ? (
                              <Loader2 className='animate-spin' />
                            ) : (
                              <RefreshCcw />
                            )}
                            同步
                          </Button>
                        )}
                        <OrderRowActions
                          order={order}
                          actionPending={isActionPending}
                          onView={() => setSelectedOrder(order)}
                          onMarkPaid={() => markPaidMutation.mutate(order.id)}
                          onThirdPartyAction={(action) =>
                            openThirdPartyDialog(order, action)
                          }
                          onLocalAction={(action) =>
                            openLocalDialog(order, action)
                          }
                        />
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={8} className='h-24 text-center'>
                    暂无订单
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </div>

        <ListPagination
          page={ordersQuery.data?.page ?? page}
          pageSize={ordersQuery.data?.pageSize ?? pageSize}
          total={ordersQuery.data?.total ?? 0}
          onPageChange={setPage}
          onPageSizeChange={(nextPageSize) => {
            setPage(1)
            setPageSize(nextPageSize)
          }}
        />
      </div>

      <Sheet
        open={!!selectedOrder}
        onOpenChange={(open) => {
          if (!open) setSelectedOrder(null)
        }}
      >
        <SheetContent className='w-full overflow-y-auto sm:max-w-3xl'>
          <SheetHeader>
            <SheetTitle>订单详情</SheetTitle>
            <SheetDescription>
              {activeOrder?.orderNo || '正在读取订单信息'}
            </SheetDescription>
          </SheetHeader>
          {activeOrder && (
            <OrderDetailContent
              order={activeOrder}
              loading={detailQuery.isFetching}
              actionPending={isActionPending}
              onMarkPaid={() => markPaidMutation.mutate(activeOrder.id)}
              onThirdPartyAction={(action) =>
                openThirdPartyDialog(activeOrder, action)
              }
              onLocalAction={(action) => openLocalDialog(activeOrder, action)}
            />
          )}
        </SheetContent>
      </Sheet>

      <ThirdPartyActionDialog
        state={thirdPartyDialog}
        form={thirdPartyForm}
        pending={thirdPartyMutation.isPending}
        onFormChange={setThirdPartyForm}
        onOpenChange={(open) => {
          if (!open) setThirdPartyDialog(null)
        }}
        onSubmit={handleThirdPartySubmit}
      />

      <LocalActionDialog
        state={localDialog}
        remark={localRemark}
        pending={localMutation.isPending}
        onRemarkChange={setLocalRemark}
        onOpenChange={(open) => {
          if (!open) setLocalDialog(null)
        }}
        onSubmit={() => {
          if (!localDialog) return
          localMutation.mutate({
            order: localDialog.order,
            action: localDialog.action,
            remark: localRemark,
          })
        }}
      />
    </AdminPage>
  )
}

function OrderRowActions({
  order,
  actionPending,
  onView,
  onMarkPaid,
  onThirdPartyAction,
  onLocalAction,
}: {
  order: OrderDetail
  actionPending: boolean
  onView: () => void
  onMarkPaid: () => void
  onThirdPartyAction: (action: ThirdPartyOrderAction | 'refresh') => void
  onLocalAction: (action: LocalOrderAction) => void
}) {
  return (
    <DropdownMenu modal={false}>
      <DropdownMenuTrigger asChild>
        <Button
          size='sm'
          variant='ghost'
          className='h-8 px-2 data-[state=open]:bg-muted'
        >
          <MoreHorizontal />
          <span className='sr-only'>打开订单操作</span>
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align='end' className='w-44'>
        <DropdownMenuItem onClick={onView}>
          <Eye />
          查看详情
        </DropdownMenuItem>
        {order.paymentStatus === 'unpaid' && (
          <DropdownMenuItem disabled={actionPending} onClick={onMarkPaid}>
            <WalletCards />
            标记已支付
          </DropdownMenuItem>
        )}
        {order.sourceType === 'third_party' ? (
          <ThirdPartyMenuItems onAction={onThirdPartyAction} />
        ) : (
          <LocalMenuItems onAction={onLocalAction} />
        )}
      </DropdownMenuContent>
    </DropdownMenu>
  )
}

function ThirdPartyMenuItems({
  onAction,
}: {
  onAction: (action: ThirdPartyOrderAction | 'refresh') => void
}) {
  return (
    <>
      <DropdownMenuSeparator />
      <DropdownMenuItem onClick={() => onAction('refresh')}>
        <FileSearch />
        查单刷新
      </DropdownMenuItem>
      <DropdownMenuItem onClick={() => onAction('budan')}>
        <RefreshCcw />
        补单
      </DropdownMenuItem>
      <DropdownMenuItem onClick={() => onAction('gaimi')}>
        <KeyRound />
        改密
      </DropdownMenuItem>
      <DropdownMenuItem onClick={() => onAction('stop')}>
        <PauseCircle />
        暂停
      </DropdownMenuItem>
      <DropdownMenuItem onClick={() => onAction('priority')}>
        <Zap />
        优先学习
      </DropdownMenuItem>
      <DropdownMenuItem onClick={() => onAction('convert')}>
        <Repeat />
        课程转换
      </DropdownMenuItem>
      <DropdownMenuItem onClick={() => onAction('update-time')}>
        <Clock />
        修改时长
      </DropdownMenuItem>
      <DropdownMenuItem onClick={() => onAction('update-cycle')}>
        <CalendarClock />
        修改周期
      </DropdownMenuItem>
    </>
  )
}

function LocalMenuItems({
  onAction,
}: {
  onAction: (action: LocalOrderAction) => void
}) {
  return (
    <>
      <DropdownMenuSeparator />
      <DropdownMenuItem onClick={() => onAction('process')}>
        <Play />
        开始处理
      </DropdownMenuItem>
      <DropdownMenuItem onClick={() => onAction('complete')}>
        <CheckCircle2 />
        完成发货
      </DropdownMenuItem>
      <DropdownMenuItem onClick={() => onAction('cancel')}>
        <XCircle />
        取消履约
      </DropdownMenuItem>
      <DropdownMenuItem onClick={() => onAction('close')}>
        <XCircle />
        关闭订单
      </DropdownMenuItem>
      <DropdownMenuItem onClick={() => onAction('remark')}>
        <SquarePen />
        更新备注
      </DropdownMenuItem>
    </>
  )
}

function OrderDetailContent({
  order,
  loading,
  actionPending,
  onMarkPaid,
  onThirdPartyAction,
  onLocalAction,
}: {
  order: OrderDetail
  loading: boolean
  actionPending: boolean
  onMarkPaid: () => void
  onThirdPartyAction: (action: ThirdPartyOrderAction | 'refresh') => void
  onLocalAction: (action: LocalOrderAction) => void
}) {
  const fulfillment = getPrimaryFulfillment(order)

  return (
    <div className='space-y-6 p-4'>
      {loading && (
        <div className='flex items-center gap-2 text-sm text-muted-foreground'>
          <Loader2 className='size-4 animate-spin' />
          正在刷新详情
        </div>
      )}

      <div className='grid gap-3 sm:grid-cols-2'>
        <InfoItem label='订单号' value={order.orderNo} />
        <InfoItem label='来源' value={sourceLabel(order.sourceType)} />
        <InfoItem label='应付金额' value={formatPrice(order.payableAmount)} />
        <InfoItem label='已付金额' value={formatPrice(order.paidAmount)} />
        <StatusItem
          label='支付状态'
          value={paymentStatusLabels[order.paymentStatus]}
          variant={paymentVariant(order.paymentStatus)}
        />
        <StatusItem
          label='履约状态'
          value={fulfillmentStatusLabels[order.fulfillmentStatus]}
          variant={fulfillmentVariant(order.fulfillmentStatus)}
        />
        <InfoItem label='第三方单号' value={fulfillment?.externalOrderNo} />
        <InfoItem label='创建时间' value={formatDateTime(order.createdAt)} />
        <InfoItem label='支付时间' value={formatDateTime(order.paidAt)} />
        <InfoItem label='关闭时间' value={formatDateTime(order.closedAt)} />
        <div className='sm:col-span-2'>
          <InfoItem label='备注' value={order.remark} />
        </div>
      </div>

      <div className='flex flex-wrap gap-2'>
        {order.paymentStatus === 'unpaid' && (
          <Button disabled={actionPending} onClick={onMarkPaid}>
            <WalletCards />
            标记已支付并履约
          </Button>
        )}
        {order.sourceType === 'third_party' ? (
          <>
            <Button
              variant='outline'
              disabled={actionPending}
              onClick={() => onThirdPartyAction('refresh')}
            >
              <FileSearch />
              查单刷新
            </Button>
            <Button
              variant='outline'
              disabled={actionPending}
              onClick={() => onThirdPartyAction('budan')}
            >
              <RefreshCcw />
              补单
            </Button>
            <Button
              variant='outline'
              disabled={actionPending}
              onClick={() => onThirdPartyAction('gaimi')}
            >
              <KeyRound />
              改密
            </Button>
          </>
        ) : (
          <>
            <Button
              variant='outline'
              disabled={actionPending}
              onClick={() => onLocalAction('process')}
            >
              <Play />
              开始处理
            </Button>
            <Button
              variant='outline'
              disabled={actionPending}
              onClick={() => onLocalAction('complete')}
            >
              <CheckCircle2 />
              完成发货
            </Button>
            <Button
              variant='outline'
              disabled={actionPending}
              onClick={() => onLocalAction('remark')}
            >
              <SquarePen />
              更新备注
            </Button>
          </>
        )}
      </div>

      <OrderItems items={order.items ?? []} />
      <Fulfillments fulfillments={order.fulfillments ?? []} />
      <OrderActions actions={order.actions ?? []} />
    </div>
  )
}

function OrderItems({ items }: { items: OrderItem[] }) {
  return (
    <DetailSection title='订单明细'>
      <div className='overflow-auto rounded-md border'>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>商品</TableHead>
              <TableHead>单价</TableHead>
              <TableHead>数量</TableHead>
              <TableHead>小计</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {items.length ? (
              items.map((item) => (
                <TableRow key={item.id}>
                  <TableCell>{item.productName}</TableCell>
                  <TableCell>{formatPrice(item.unitPrice)}</TableCell>
                  <TableCell>{item.quantity}</TableCell>
                  <TableCell>{formatPrice(item.totalAmount)}</TableCell>
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell colSpan={4} className='h-20 text-center'>
                  暂无明细
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>
      {items[0]?.payload && (
        <PayloadBlock title='下单信息' value={items[0].payload} />
      )}
    </DetailSection>
  )
}

function Fulfillments({
  fulfillments,
}: {
  fulfillments: OrderFulfillment[]
}) {
  return (
    <DetailSection title='履约记录'>
      <div className='space-y-3'>
        {fulfillments.length ? (
          fulfillments.map((item) => (
            <div key={item.id} className='rounded-md border p-3'>
              <div className='flex flex-wrap items-center justify-between gap-2'>
                <div className='font-medium'>{item.fulfillmentType}</div>
                <Badge variant={fulfillmentVariant(item.status)}>
                  {fulfillmentStatusLabels[item.status]}
                </Badge>
              </div>
              <div className='mt-3 grid gap-3 sm:grid-cols-2'>
                <InfoItem label='第三方单号' value={item.externalOrderNo} />
                <InfoItem label='提交时间' value={formatDateTime(item.submittedAt)} />
                <InfoItem label='完成时间' value={formatDateTime(item.completedAt)} />
                <InfoItem label='错误信息' value={item.errorMessage} />
              </div>
              <div className='mt-3 grid gap-3'>
                <PayloadBlock title='请求摘要' value={item.requestPayload} />
                <PayloadBlock title='响应摘要' value={item.responsePayload} />
              </div>
            </div>
          ))
        ) : (
          <div className='rounded-md border px-3 py-8 text-center text-sm text-muted-foreground'>
            暂无履约记录
          </div>
        )}
      </div>
    </DetailSection>
  )
}

function OrderActions({ actions }: { actions: OrderAction[] }) {
  return (
    <DetailSection title='操作流水'>
      <div className='space-y-3'>
        {actions.length ? (
          actions.map((item) => (
            <div key={item.id} className='rounded-md border p-3'>
              <div className='flex flex-wrap items-center justify-between gap-2'>
                <div className='font-medium'>{item.action}</div>
                <Badge variant={actionStatusVariant(item.status)}>
                  {item.status === 'success' ? '成功' : '失败'}
                </Badge>
              </div>
              <div className='mt-1 text-xs text-muted-foreground'>
                {formatDateTime(item.createdAt)}
              </div>
              <div className='mt-3 grid gap-3'>
                <InfoItem label='备注' value={item.remark} />
                <InfoItem label='错误信息' value={item.errorMessage} />
                <PayloadBlock title='请求摘要' value={item.requestPayload} />
                <PayloadBlock title='响应摘要' value={item.responsePayload} />
              </div>
            </div>
          ))
        ) : (
          <div className='rounded-md border px-3 py-8 text-center text-sm text-muted-foreground'>
            暂无操作流水
          </div>
        )}
      </div>
    </DetailSection>
  )
}

function ThirdPartyActionDialog({
  state,
  form,
  pending,
  onFormChange,
  onOpenChange,
  onSubmit,
}: {
  state: ThirdPartyDialogState | null
  form: ThirdPartyActionForm
  pending: boolean
  onFormChange: (form: ThirdPartyActionForm) => void
  onOpenChange: (open: boolean) => void
  onSubmit: () => void
}) {
  const action = state?.action
  const title = action ? thirdPartyActionLabels[action] : '第三方订单操作'
  const showGaimiFields = action === 'gaimi'
  const showConvert = action === 'convert'
  const showTime = action === 'update-time'
  const showCycle = action === 'update-cycle'

  return (
    <Dialog open={!!state} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
          <DialogDescription>
            第三方订单 ID 可留空，系统会优先使用履约记录中的第三方单号。
          </DialogDescription>
        </DialogHeader>
        <div className='grid gap-4'>
          <FieldInput
            label='第三方订单 ID'
            value={form.externalOrderNo}
            placeholder='留空使用已保存的第三方单号'
            onChange={(value) =>
              onFormChange({ ...form, externalOrderNo: value })
            }
          />
          {action === 'refresh' && (
            <FieldInput
              label='下单账号'
              value={form.username}
              placeholder='第三方单号为空时用于查单'
              onChange={(value) => onFormChange({ ...form, username: value })}
            />
          )}
          {showGaimiFields && (
            <>
              <FieldInput
                label='新密码'
                value={form.newPwd}
                type='password'
                onChange={(value) => onFormChange({ ...form, newPwd: value })}
              />
              <FieldInput
                label='恐龙备注'
                value={form.remark}
                placeholder='支持英文逗号分隔'
                onChange={(value) => onFormChange({ ...form, remark: value })}
              />
              <FieldInput
                label='代理城市'
                value={form.city}
                onChange={(value) => onFormChange({ ...form, city: value })}
              />
              <FieldInput
                label='归属标记'
                value={form.tag}
                onChange={(value) => onFormChange({ ...form, tag: value })}
              />
              <div className='grid gap-2'>
                <Label>自动补单</Label>
                <Select
                  value={form.autoReset}
                  onValueChange={(value) =>
                    onFormChange({ ...form, autoReset: value })
                  }
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value='0'>关闭</SelectItem>
                    <SelectItem value='1'>开启</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className='grid gap-2'>
                <Label>动态配置 JSON</Label>
                <Textarea
                  value={form.config}
                  className='min-h-24 font-mono text-xs'
                  placeholder='{"useTime":60,"code":"888888"}'
                  onChange={(event) =>
                    onFormChange({ ...form, config: event.target.value })
                  }
                />
              </div>
            </>
          )}
          {showConvert && (
            <FieldInput
              label='目标课程 ID'
              value={form.convertToClassId}
              placeholder='例如 182 或 183'
              onChange={(value) =>
                onFormChange({ ...form, convertToClassId: value })
              }
            />
          )}
          {showTime && (
            <FieldInput
              label='时长（小时）'
              value={form.time}
              type='number'
              onChange={(value) => onFormChange({ ...form, time: value })}
            />
          )}
          {showCycle && (
            <FieldInput
              label='周期（天）'
              value={form.cycle}
              type='number'
              onChange={(value) => onFormChange({ ...form, cycle: value })}
            />
          )}
        </div>
        <DialogFooter>
          <Button variant='outline' onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button disabled={pending} onClick={onSubmit}>
            {pending && <Loader2 className='animate-spin' />}
            提交
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}

function LocalActionDialog({
  state,
  remark,
  pending,
  onRemarkChange,
  onOpenChange,
  onSubmit,
}: {
  state: LocalDialogState | null
  remark: string
  pending: boolean
  onRemarkChange: (value: string) => void
  onOpenChange: (open: boolean) => void
  onSubmit: () => void
}) {
  const title = state ? localActionLabels[state.action] : '自营订单操作'
  const descriptions: Record<LocalOrderAction, string> = useMemo(
    () => ({
      process: '将自营订单履约状态更新为处理中。',
      complete: '将自营订单履约状态更新为已完成。',
      cancel: '取消本地履约，不会发起第三方请求。',
      close: '关闭未支付订单，并取消本地履约。',
      remark: '更新订单备注，方便后续售后和人工处理。',
    }),
    []
  )

  return (
    <Dialog open={!!state} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
          <DialogDescription>
            {state ? descriptions[state.action] : ''}
          </DialogDescription>
        </DialogHeader>
        <div className='grid gap-2'>
          <Label>备注</Label>
          <Textarea
            value={remark}
            className='min-h-24'
            onChange={(event) => onRemarkChange(event.target.value)}
          />
        </div>
        <DialogFooter>
          <Button variant='outline' onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button disabled={pending} onClick={onSubmit}>
            {pending && <Loader2 className='animate-spin' />}
            提交
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}

function DetailSection({
  title,
  children,
}: {
  title: string
  children: ReactNode
}) {
  return (
    <section className='space-y-3'>
      <h3 className='text-sm font-semibold'>{title}</h3>
      {children}
    </section>
  )
}

function InfoItem({
  label,
  value,
}: {
  label: string
  value?: string | null
}) {
  return (
    <div className='grid gap-1'>
      <div className='text-xs text-muted-foreground'>{label}</div>
      <div className='min-h-8 rounded-md border bg-muted/30 px-3 py-2 text-sm break-all'>
        {value || '-'}
      </div>
    </div>
  )
}

function StatusItem({
  label,
  value,
  variant,
}: {
  label: string
  value: string
  variant: 'default' | 'secondary' | 'destructive' | 'outline'
}) {
  return (
    <div className='grid gap-1'>
      <div className='text-xs text-muted-foreground'>{label}</div>
      <div className='min-h-8 rounded-md border bg-muted/30 px-3 py-2'>
        <Badge variant={variant}>{value}</Badge>
      </div>
    </div>
  )
}

function FieldInput({
  label,
  value,
  placeholder,
  type = 'text',
  onChange,
}: {
  label: string
  value: string
  placeholder?: string
  type?: string
  onChange: (value: string) => void
}) {
  return (
    <div className='grid gap-2'>
      <Label>{label}</Label>
      <Input
        value={value}
        type={type}
        placeholder={placeholder}
        onChange={(event) => onChange(event.target.value)}
      />
    </div>
  )
}

function PayloadBlock({ title, value }: { title: string; value: unknown }) {
  return (
    <div className='grid gap-1'>
      <div className='text-xs text-muted-foreground'>{title}</div>
      <pre className='max-h-56 overflow-auto rounded-md border bg-muted/30 p-3 text-xs whitespace-pre-wrap break-all'>
        {stringifyPayload(value)}
      </pre>
    </div>
  )
}
