import { App, Input, InputNumber, Typography } from 'antd'
import { useRef, useState } from 'react'

import { updateAdminWorkOrder } from '@/services/admin'
import type { WorkOrder } from '@/types/worker-platform'

import { formatMoney } from './shared'
import { getUserPaymentFen } from './work-order-panel-utils'

/** 商品名：单击看详情，双击原地修改（仅未接走工单） */
export function ProductNameEditableCell({
  order,
  onOpenDetail,
  onSaved,
}: {
  order: WorkOrder
  onOpenDetail: () => void
  onSaved: () => Promise<void> | void
}) {
  const { message } = App.useApp()
  const [editing, setEditing] = useState(false)
  const [draft, setDraft] = useState('')
  const savingRef = useRef(false)
  const clickTimerRef = useRef<number | null>(null)
  const editable = order.capabilities?.canEdit === true

  function handleClick() {
    if (clickTimerRef.current) window.clearTimeout(clickTimerRef.current)
    clickTimerRef.current = window.setTimeout(() => onOpenDetail(), 260)
  }

  function handleDoubleClick() {
    if (clickTimerRef.current) {
      window.clearTimeout(clickTimerRef.current)
      clickTimerRef.current = null
    }
    if (!editable) return
    setDraft(order.productName || '')
    setEditing(true)
  }

  async function save() {
    if (savingRef.current) return
    const next = draft.trim()
    if (!next) {
      message.error('商品名不能为空')
      return
    }
    if (next === order.productName) {
      setEditing(false)
      return
    }
    savingRef.current = true
    try {
      await updateAdminWorkOrder(order.workOrderId, { productName: next })
      message.success('商品名已更新')
      setEditing(false)
      await onSaved()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '保存失败')
    } finally {
      savingRef.current = false
    }
  }

  if (!editing) {
    return (
      <Typography.Link
        title={editable ? '双击修改商品名' : undefined}
        onClick={handleClick}
        onDoubleClick={handleDoubleClick}
      >
        {order.productName || '未命名商品'}
      </Typography.Link>
    )
  }

  return (
    <Input
      autoFocus
      size="small"
      style={{ width: 200 }}
      value={draft}
      onChange={(event) => setDraft(event.target.value)}
      onPressEnter={() => void save()}
      onBlur={() => void save()}
      onKeyDown={(event) => {
        if (event.key === 'Escape') setEditing(false)
      }}
    />
  )
}

export function AmountEditableCell({
  order,
  field,
  onSaved,
}: {
  order: WorkOrder
  field: 'rewardAmount' | 'requiredDepositAmount'
  onSaved: () => Promise<void> | void
}) {
  const { message, modal } = App.useApp()
  const [editing, setEditing] = useState(false)
  const [draft, setDraft] = useState<number | null>(null)
  const savingRef = useRef(false)
  const editable = order.capabilities?.canEdit === true
  const currentFen = Number(order[field] || 0)
  const currentYuan = currentFen / 100
  const paymentFen = field === 'rewardAmount' ? getUserPaymentFen(order) : null
  const isLossOrder = paymentFen !== null && currentFen > paymentFen

  async function doSave(nextYuan: number) {
    if (savingRef.current) return
    savingRef.current = true
    try {
      await updateAdminWorkOrder(order.workOrderId, { [field]: nextYuan })
      message.success('金额已更新')
      setEditing(false)
      await onSaved()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '保存失败')
    } finally {
      savingRef.current = false
    }
  }

  async function save() {
    if (savingRef.current) return
    if (draft === null || !Number.isFinite(Number(draft))) {
      setEditing(false)
      return
    }
    const nextYuan = Number(draft)
    if (nextYuan < 0) {
      message.error('金额不能为负数')
      return
    }
    if (Math.abs(nextYuan - currentYuan) < 0.005) {
      setEditing(false)
      return
    }
    const nextFen = Math.round(nextYuan * 100)
    if (paymentFen !== null && nextFen > paymentFen) {
      modal.confirm({
        title: '发单金额高于用户付款金额',
        content: (
          <span>
            该订单用户付款 {formatMoney(paymentFen)}，发单金额{' '}
            <Typography.Text strong type="danger">
              {formatMoney(nextFen)}
            </Typography.Text>
            ，本单平台将亏损。确认保存？
          </span>
        ),
        okText: '确认保存',
        cancelText: '取消',
        onOk: () => doSave(nextYuan),
      })
      return
    }
    await doSave(nextYuan)
  }

  if (!editing) {
    return (
      <Typography.Text
        title={editable ? '双击修改金额' : undefined}
        strong={isLossOrder}
        type={isLossOrder ? 'danger' : undefined}
        style={{
          cursor: editable ? 'pointer' : 'default',
          ...(editable && !isLossOrder ? { color: 'rgba(0,0,0,0.65)' } : {}),
        }}
        onDoubleClick={() => {
          if (!editable) return
          setDraft(currentYuan)
          setEditing(true)
        }}
      >
        {formatMoney(currentFen)}
      </Typography.Text>
    )
  }

  return (
    <InputNumber
      autoFocus
      size="small"
      min={0}
      precision={2}
      step={1}
      style={{ width: 92 }}
      value={draft}
      onChange={setDraft}
      onFocus={(event) => event.target.select()}
      onPressEnter={() => void save()}
      onBlur={() => void save()}
      onKeyDown={(event) => {
        if (event.key === 'Escape') setEditing(false)
      }}
    />
  )
}
