import { Tag, Typography } from 'antd'
import type { TableColumnsType } from 'antd'

import type {
  WorkerFinanceRequest,
  WorkerProfileSummary,
  WorkerUser,
  WorkerWalletLedger,
} from '@/types/worker-platform'
import { formatDateTime } from '@/utils/date-time'

export function resolveAvailableForWithdraw(
  worker: WorkerUser | undefined,
  _summary: WorkerProfileSummary | undefined,
) {
  // 提现申请即冻结 available_amount，可提现口径就是当前可用余额，无需再减待处理申请。
  return Math.max(0, Number(worker?.wallet.availableAmount || 0))
}

export function resolveWorkerInitial(worker: WorkerUser | undefined) {
  return String(worker?.displayName || worker?.username || '打')
    .trim()
    .slice(0, 1)
    .toUpperCase()
}

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

export function formatWorkerStatus(status: string) {
  if (status === 'active') return '已启用'
  if (status === 'pending_review') return '待处理'
  if (status === 'rejected') return '已冻结'
  if (status === 'disabled') return '已停用'
  return status || '-'
}

export function resolveWorkerStatusColor(status: string) {
  if (status === 'active') return 'green'
  if (status === 'pending_review') return 'gold'
  if (status === 'rejected') return 'red'
  if (status === 'disabled') return 'default'
  return 'blue'
}

export function formatLedgerType(ledgerType: string) {
  const labels: Record<string, string> = {
    manual_credit: '人工充值',
    withdraw_freeze: '提现冻结',
    withdraw_paid: '提现打款',
    withdraw_release: '提现退回',
    deposit_freeze: '冻结押金',
    deposit_release: '释放押金',
    deposit_pending_unfreeze: '待解冻金额',
    reward_pending_unfreeze: '报酬待解冻',
    deposit_unfreeze: '押金已解冻',
    reward_unfreeze: '报酬已解冻',
    deposit_deduction: '扣除押金',
    reward_settlement: '结算报酬',
    sharing_reward: '拼单报酬',
    after_sales_deposit_deduction: '售后扣减押金',
    after_sales_balance_deduction: '售后扣减余额',
    after_sales_debt_offset: '抵扣售后欠款',
    after_sales_refund: '售后追缴退还',
  }
  return labels[ledgerType] || ledgerType || '-'
}

export function resolveLedgerTagColor(ledgerType: string) {
  if (ledgerType === 'manual_credit') return 'blue'
  if (ledgerType === 'withdraw_freeze') return 'orange'
  if (ledgerType === 'withdraw_paid') return 'purple'
  if (ledgerType === 'withdraw_release') return 'green'
  if (ledgerType === 'deposit_freeze') return 'gold'
  if (ledgerType === 'deposit_release') return 'green'
  if (ledgerType === 'deposit_pending_unfreeze') return 'orange'
  if (ledgerType === 'reward_pending_unfreeze') return 'orange'
  if (ledgerType === 'deposit_unfreeze') return 'green'
  if (ledgerType === 'reward_unfreeze') return 'green'
  if (ledgerType === 'deposit_deduction') return 'red'
  if (ledgerType === 'reward_settlement') return 'cyan'
  if (ledgerType === 'sharing_reward') return 'cyan'
  if (ledgerType === 'after_sales_deposit_deduction') return 'red'
  if (ledgerType === 'after_sales_balance_deduction') return 'red'
  if (ledgerType === 'after_sales_debt_offset') return 'orange'
  if (ledgerType === 'after_sales_refund') return 'green'
  return 'default'
}

export function resolveLedgerFrozenAmountLabel(ledgerType: string) {
  return ['withdraw_freeze', 'withdraw_paid', 'withdraw_release'].includes(ledgerType)
    ? '提现冻结'
    : '冻结押金'
}

export function formatRequestType(requestType: string) {
  if (requestType === 'recharge') return '充值申请'
  if (requestType === 'withdraw') return '提现申请'
  return requestType || '-'
}

export function formatRequestStatus(status: string) {
  const labels: Record<string, string> = {
    pending: '待处理',
    approved: '已通过',
    rejected: '已拒绝',
    cancelled: '已取消',
  }
  return labels[status] || status || '-'
}

export function hasRechargeConfig(
  financeConfig:
    | {
        recharge?: { accountName?: string; accountNo?: string; qrCodeImage?: unknown }
      }
    | undefined,
) {
  return Boolean(
    financeConfig?.recharge?.accountName ||
    financeConfig?.recharge?.accountNo ||
    financeConfig?.recharge?.qrCodeImage,
  )
}

export function renderRechargeRequestSummary(row: WorkerFinanceRequest) {
  const snapshot = getRechargeSnapshot(row)
  if (!snapshot.channelName && !snapshot.accountName && !snapshot.accountNo) {
    return <Typography.Text type="secondary">线下充值，等待管理员入账</Typography.Text>
  }

  return (
    <div className="cell-stack">
      <Typography.Text>
        {[snapshot.channelName, snapshot.accountName].filter(Boolean).join(' / ') || '线下充值'}
      </Typography.Text>
      <Typography.Text type="secondary">
        {snapshot.accountNo ? maskAccountNo(snapshot.accountNo) : '等待管理员核对'}
      </Typography.Text>
    </div>
  )
}

export function resolveRequestStatusColor(status: string) {
  if (status === 'approved') return 'green'
  if (status === 'pending') return 'gold'
  if (status === 'rejected') return 'red'
  if (status === 'cancelled') return 'default'
  return 'blue'
}

export function formatWithdrawChannel(channel: string) {
  if (channel === 'alipay') return '支付宝'
  if (channel === 'wechat') return '微信收款'
  if (channel === 'bank') return '银行卡'
  return channel || '-'
}

export function maskAccountNo(value: string) {
  const text = String(value || '').trim()
  if (!text) return '-'
  if (text.length <= 8) return text
  return `${text.slice(0, 4)} **** ${text.slice(-4)}`
}

export const workerLedgerColumns: TableColumnsType<WorkerWalletLedger> = [
  {
    title: '时间',
    dataIndex: 'createdAt',
    width: 180,
    render: (value) => formatDateTime(String(value || '')),
  },
  {
    title: '类型',
    width: 150,
    render: (_, row) => (
      <Tag color={resolveLedgerTagColor(row.ledgerType)}>{formatLedgerType(row.ledgerType)}</Tag>
    ),
  },
  {
    title: '金额',
    width: 120,
    render: (_, row) => (
      <Typography.Text
        strong
        className={row.amount >= 0 ? 'worker-amount-positive' : 'worker-amount-negative'}
      >
        {row.amount >= 0 ? '+' : ''}
        {formatMoney(row.amount)}
      </Typography.Text>
    ),
  },
  { title: '余额', width: 120, render: (_, row) => formatMoney(row.balanceAfter) },
  { title: '冻结金额', width: 120, render: (_, row) => formatMoney(row.frozenAfter) },
  {
    title: '说明',
    minWidth: 260,
    render: (_, row) => (
      <div className="cell-stack">
        <Typography.Text>{row.note || '-'}</Typography.Text>
        {row.relatedPlatformOrderId ? (
          <Typography.Text type="secondary">订单号 {row.relatedPlatformOrderId}</Typography.Text>
        ) : null}
      </div>
    ),
  },
]

export const workerFinanceRequestColumns: TableColumnsType<WorkerFinanceRequest> = [
  {
    title: '申请时间',
    dataIndex: 'createdAt',
    width: 180,
    render: (value) => formatDateTime(String(value || '')),
  },
  {
    title: '类型',
    width: 120,
    render: (_, row) => (
      <Tag color={row.requestType === 'withdraw' ? 'green' : 'blue'}>
        {formatRequestType(row.requestType)}
      </Tag>
    ),
  },
  {
    title: '金额',
    width: 120,
    render: (_, row) => <Typography.Text strong>{formatMoney(row.amount)}</Typography.Text>,
  },
  {
    title: '收款信息',
    minWidth: 220,
    render: (_, row) =>
      row.requestType === 'withdraw' ? (
        <div className="cell-stack">
          <Typography.Text>
            {formatWithdrawChannel(row.accountChannel)} / {row.accountName || '-'}
          </Typography.Text>
          <Typography.Text type="secondary">{maskAccountNo(row.accountNo)}</Typography.Text>
        </div>
      ) : (
        renderRechargeRequestSummary(row)
      ),
  },
  {
    title: '状态',
    width: 130,
    render: (_, row) => (
      <Tag color={resolveRequestStatusColor(row.status)}>{formatRequestStatus(row.status)}</Tag>
    ),
  },
  {
    title: '备注',
    minWidth: 260,
    render: (_, row) => (
      <div className="cell-stack">
        <Typography.Text>{row.note || '-'}</Typography.Text>
        {row.reviewedNote ? (
          <Typography.Text type="secondary">审核备注：{row.reviewedNote}</Typography.Text>
        ) : null}
      </div>
    ),
  },
]

function getRechargeSnapshot(row: WorkerFinanceRequest) {
  const payload = asRecord(row.payload)
  const financeConfig = asRecord(payload.financeConfig)
  return {
    channelName: String(financeConfig.channelName || '').trim(),
    accountName: String(financeConfig.accountName || '').trim(),
    accountNo: String(financeConfig.accountNo || '').trim(),
  }
}

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