import {
  BankOutlined,
  CopyOutlined,
  CustomerServiceOutlined,
  LockOutlined,
  LogoutOutlined,
  ReloadOutlined,
  WalletOutlined,
} from '@ant-design/icons'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import {
  Alert,
  App,
  Avatar,
  Button,
  Card,
  DatePicker,
  Descriptions,
  Empty,
  Form,
  Image,
  Input,
  InputNumber,
  Modal,
  Progress,
  Select,
  Space,
  Table,
  Tabs,
  Tag,
  Typography,
} from 'antd'
import type { TableColumnsType } from 'antd'
import { useState } from 'react'
import { useNavigate } from 'react-router'

import ImageUpload from '@/components/files/ImageUpload'
import {
  changeWorkerPassword,
  createWorkerRechargeRequest,
  createWorkerWithdrawRequest,
  fetchWorkerFinanceRequests,
  fetchWorkerProfile,
  fetchWorkerWalletLedgers,
  logoutWorker,
} from '@/services/worker'
import type {
  UploadedFile,
  WorkerFinanceRequest,
  WorkerProfileSummary,
  WorkerUser,
  WorkerWalletLedger,
} from '@/types/worker-platform'
import { formatDateTime } from '@/utils/date-time'
import { clearWorkerSession } from '@/utils/worker-auth'

type RechargeFormValues = {
  amount?: number
  note?: string
  paidAt?: string
  proofFiles?: UploadedFile[]
}

type WithdrawFormValues = {
  amount?: number
  accountChannel?: string
  accountName?: string
  accountNo?: string
  note?: string
}

type PasswordFormValues = {
  currentPassword?: string
  newPassword?: string
  confirmPassword?: string
}

export default function WorkerProfilePage() {
  const { message } = App.useApp()
  const navigate = useNavigate()
  const queryClient = useQueryClient()

  const [activeTab, setActiveTab] = useState('account')
  const [ledgerPage, setLedgerPage] = useState(1)
  const [ledgerPageSize, setLedgerPageSize] = useState(10)
  const [ledgerType, setLedgerType] = useState('')
  const [requestPage, setRequestPage] = useState(1)
  const [requestPageSize, setRequestPageSize] = useState(10)
  const [requestType, setRequestType] = useState('')
  const [requestStatus, setRequestStatus] = useState('')
  const [rechargeOpen, setRechargeOpen] = useState(false)
  const [withdrawOpen, setWithdrawOpen] = useState(false)
  const [passwordOpen, setPasswordOpen] = useState(false)
  const [contactOpen, setContactOpen] = useState(false)
  const [submittingRecharge, setSubmittingRecharge] = useState(false)
  const [submittingWithdraw, setSubmittingWithdraw] = useState(false)
  const [submittingPassword, setSubmittingPassword] = useState(false)
  const [rechargeForm] = Form.useForm<RechargeFormValues>()
  const [withdrawForm] = Form.useForm<WithdrawFormValues>()
  const [passwordForm] = Form.useForm<PasswordFormValues>()

  const profileQuery = useQuery({
    queryKey: ['worker-profile'],
    queryFn: () => fetchWorkerProfile(),
    retry: false,
  })

  const worker = profileQuery.data?.data.worker
  const summary = profileQuery.data?.data.summary
  const levelProgress = profileQuery.data?.data.levelProgress
  const financeConfig = profileQuery.data?.data.financeConfig
  const canUseFinanceActions = worker?.status === 'active'

  async function copyInviteCode() {
    if (!worker?.inviteCode) return
    try {
      await navigator.clipboard.writeText(worker.inviteCode)
      message.success('邀请码已复制')
    } catch {
      message.error('复制失败，请手动复制')
    }
  }

  const ledgersQuery = useQuery({
    queryKey: ['worker-wallet-ledgers', ledgerType, ledgerPage, ledgerPageSize],
    queryFn: () =>
      fetchWorkerWalletLedgers({
        page: ledgerPage,
        pageSize: ledgerPageSize,
        ledgerType,
      }),
    enabled: Boolean(worker),
    retry: false,
  })

  const requestsQuery = useQuery({
    queryKey: [
      'worker-finance-requests',
      requestType,
      requestStatus,
      requestPage,
      requestPageSize,
    ],
    queryFn: () =>
      fetchWorkerFinanceRequests({
        page: requestPage,
        pageSize: requestPageSize,
        requestType,
        status: requestStatus,
      }),
    enabled: Boolean(worker),
    retry: false,
  })

  async function refreshAll() {
    await Promise.all([
      queryClient.invalidateQueries({ queryKey: ['worker-profile'] }),
      queryClient.invalidateQueries({ queryKey: ['worker-wallet-ledgers'] }),
      queryClient.invalidateQueries({ queryKey: ['worker-finance-requests'] }),
    ])
  }

  async function submitLogout() {
    try {
      await logoutWorker()
    } catch {
      // 接单端退出为无状态操作，本地清理优先。
    } finally {
      clearWorkerSession()
      message.success('已退出登录')
      navigate('/worker/login', { replace: true })
    }
  }

  function jumpToLedgerSection(nextLedgerType = '') {
    setLedgerType(nextLedgerType)
    setLedgerPage(1)
    setActiveTab('ledger')
  }

  function jumpToRequestSection(nextRequestType = '', nextStatus = '') {
    setRequestType(nextRequestType)
    setRequestStatus(nextStatus)
    setRequestPage(1)
    setActiveTab('requests')
  }

  function openRechargeModal() {
    if (!canUseFinanceActions) {
      message.warning('当前账号尚未通过审核，暂时不能发起充值申请')
      return
    }
    if (financeConfig?.recharge.enabled === false) {
      message.warning('当前充值入口暂未开放，请联系管理员')
      return
    }
    setRechargeOpen(true)
  }

  function openWithdrawModal() {
    if (!canUseFinanceActions) {
      message.warning('当前账号尚未通过审核，暂时不能发起提现申请')
      return
    }
    if (financeConfig?.withdraw.enabled === false) {
      message.warning('当前提现入口暂未开放，请联系管理员')
      return
    }
    setWithdrawOpen(true)
  }

  async function submitRecharge(values: RechargeFormValues) {
    setSubmittingRecharge(true)
    try {
      await createWorkerRechargeRequest({
        amount: values.amount,
        note: String(values.note || '').trim(),
        paidAt: values.paidAt || '',
        proofFiles: values.proofFiles || [],
      })
      message.success('充值申请已提交，请等待管理员处理')
      setRechargeOpen(false)
      rechargeForm.resetFields()
      await refreshAll()
      jumpToRequestSection('recharge')
    } catch (error) {
      message.error(error instanceof Error ? error.message : '提交充值申请失败')
    } finally {
      setSubmittingRecharge(false)
    }
  }

  async function submitWithdraw(values: WithdrawFormValues) {
    setSubmittingWithdraw(true)
    try {
      await createWorkerWithdrawRequest({
        amount: values.amount,
        accountChannel: values.accountChannel,
        accountName: String(values.accountName || '').trim(),
        accountNo: String(values.accountNo || '').trim(),
        note: String(values.note || '').trim(),
      })
      message.success('提现申请已提交，请等待管理员审核')
      setWithdrawOpen(false)
      withdrawForm.resetFields()
      await refreshAll()
      jumpToRequestSection('withdraw')
    } catch (error) {
      message.error(error instanceof Error ? error.message : '提交提现申请失败')
    } finally {
      setSubmittingWithdraw(false)
    }
  }

  async function submitPasswordChange(values: PasswordFormValues) {
    setSubmittingPassword(true)
    try {
      await changeWorkerPassword({
        currentPassword: String(values.currentPassword || ''),
        newPassword: String(values.newPassword || ''),
      })
      message.success('密码已修改，请重新登录')
      clearWorkerSession()
      navigate('/worker/login', { replace: true })
    } catch (error) {
      message.error(error instanceof Error ? error.message : '修改密码失败')
    } finally {
      setSubmittingPassword(false)
    }
  }

  const ledgerColumns: 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.relatedWorkOrderId ? (
            <Typography.Text type="secondary">
              关联工单 #{row.relatedWorkOrderId}
            </Typography.Text>
          ) : null}
        </div>
      ),
    },
  ]

  const requestColumns: 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>
      ),
    },
  ]

  if (profileQuery.error) {
    return (
      <section className="page-stack">
        <div className="worker-page-head">
          <Typography.Title level={3}>个人中心</Typography.Title>
          <Button
            icon={<ReloadOutlined />}
            loading={profileQuery.isFetching}
            onClick={() => refreshAll()}
          >
            刷新
          </Button>
        </div>
        <Card>
          <Typography.Text type="danger">
            {profileQuery.error instanceof Error ? profileQuery.error.message : '读取个人中心失败'}
          </Typography.Text>
        </Card>
      </section>
    )
  }

  return (
    <section className="page-stack">
      <div className="worker-page-head">
        <Typography.Title level={3}>个人中心</Typography.Title>
        <Button
          icon={<ReloadOutlined />}
          loading={
            profileQuery.isFetching || ledgersQuery.isFetching || requestsQuery.isFetching
          }
          onClick={() => refreshAll()}
        >
          刷新
        </Button>
      </div>

      {!worker && !profileQuery.isLoading ? <Empty description="暂无打手信息" /> : null}

      {worker ? (
        <Space direction="vertical" size={16} style={{ width: '100%' }}>
          {!canUseFinanceActions ? (
            <Alert
              showIcon
              type="warning"
              message="当前账号尚未通过审核，充值申请、提现申请和接单功能暂不可用。"
            />
          ) : null}

          <Card size="small">
            <Space size={16} wrap align="start">
              <Avatar size={64}>
                {resolveWorkerInitial(worker)}
              </Avatar>
              <Space direction="vertical" size={2}>
                <Typography.Title level={4} style={{ margin: 0 }}>
                  {worker.displayName || worker.username}
                </Typography.Title>
                <Typography.Text type="secondary">
                  账号：{worker.username}
                </Typography.Text>
                <Typography.Text type="secondary">
                  手机号：{worker.phone || '-'}
                </Typography.Text>
              </Space>
              <Space size={[8, 8]} wrap>
                <Tag color={resolveWorkerStatusColor(worker.status)}>
                  {formatWorkerStatus(worker.status)}
                </Tag>
                <Tag>{worker.level?.name || '未分级'}</Tag>
              </Space>
            </Space>
            <Space direction="vertical" size={4} style={{ marginTop: 12, width: '100%' }}>
              <Space wrap size={[8, 8]}>
                <Typography.Text type="secondary">
                  我的邀请码：
                </Typography.Text>
                <Typography.Text strong>{worker.inviteCode || '-'}</Typography.Text>
                <Button
                  size="small"
                  type="link"
                  icon={<CopyOutlined />}
                  disabled={!worker.inviteCode}
                  onClick={copyInviteCode}
                >
                  复制
                </Button>
              </Space>
              {levelProgress && levelProgress.nextThreshold !== null ? (
                <Space direction="vertical" size={0} style={{ width: '100%' }}>
                  <Typography.Text type="secondary">
                    已累计完成 {summary?.acceptedOrderCount || 0} 单，
                    距下一等级还需 {Math.max(0, levelProgress.nextThreshold - (summary?.acceptedOrderCount || 0))} 单
                  </Typography.Text>
                  <Progress
                    percent={levelProgress.progressPercent}
                    size="small"
                    format={(percent) => `${percent}%`}
                  />
                </Space>
              ) : (
                <Typography.Text type="secondary">
                  已累计完成 {summary?.acceptedOrderCount || 0} 单，当前已是最高等级
                </Typography.Text>
              )}
            </Space>
          </Card>

          <Card size="small" className="worker-profile-wallet-card">
            <div className="worker-profile-wallet-strip">
              <div className="worker-profile-wallet-item">
                <span className="worker-profile-wallet-label">可用余额</span>
                <strong className="worker-profile-wallet-value">
                  {formatMoney(worker.wallet.availableAmount)}
                </strong>
                <small className="worker-profile-wallet-note">可用于抢单冻结或提现申请</small>
              </div>
              <div className="worker-profile-wallet-item">
                <span className="worker-profile-wallet-label">冻结押金</span>
                <strong className="worker-profile-wallet-value">
                  {formatMoney(worker.wallet.frozenDepositAmount)}
                </strong>
                <small className="worker-profile-wallet-note">抢单后冻结，验收后进入待解冻</small>
              </div>
              <div className="worker-profile-wallet-item">
                <span className="worker-profile-wallet-label">待解冻押金</span>
                <strong className="worker-profile-wallet-value">
                  {formatMoney(worker.wallet.pendingUnfreezeAmount)}
                </strong>
                <small className="worker-profile-wallet-note">验收后按配置天数解冻到账</small>
              </div>
              <div className="worker-profile-wallet-item">
                <span className="worker-profile-wallet-label">累计结算</span>
                <strong className="worker-profile-wallet-value">
                  {formatMoney(worker.wallet.totalSettledAmount)}
                </strong>
                <small className="worker-profile-wallet-note">已结算入账的报酬合计</small>
              </div>
            </div>
          </Card>

          <Card title="快捷操作" size="small">
            <Space wrap size={[12, 12]}>
              <Button
                type="primary"
                icon={<WalletOutlined />}
                disabled={!canUseFinanceActions}
                onClick={openRechargeModal}
              >
                充值申请
              </Button>
              <Button
                type="primary"
                icon={<BankOutlined />}
                disabled={!canUseFinanceActions}
                onClick={openWithdrawModal}
              >
                提现申请
              </Button>
              <Button icon={<LockOutlined />} onClick={() => setPasswordOpen(true)}>
                修改密码
              </Button>
              <Button
                icon={<CustomerServiceOutlined />}
                onClick={() => setContactOpen(true)}
              >
                联系管理员
              </Button>
              <Button danger icon={<LogoutOutlined />} onClick={submitLogout}>
                退出登录
              </Button>
            </Space>
          </Card>

          <Tabs
            activeKey={activeTab}
            onChange={setActiveTab}
            items={[
              {
                key: 'account',
                label: '账号信息',
                children: (
                  <Card size="small">
                    <Descriptions column={{ xs: 1, md: 2 }} bordered size="small">
                      <Descriptions.Item label="账号">{worker.username}</Descriptions.Item>
                      <Descriptions.Item label="昵称">
                        {worker.displayName || '-'}
                      </Descriptions.Item>
                      <Descriptions.Item label="手机号">
                        {worker.phone || '-'}
                      </Descriptions.Item>
                      <Descriptions.Item label="审核状态">
                        <Tag color={resolveWorkerStatusColor(worker.status)}>
                          {formatWorkerStatus(worker.status)}
                        </Tag>
                      </Descriptions.Item>
                      <Descriptions.Item label="当前等级">
                        {worker.level?.name || '-'}
                      </Descriptions.Item>
                      <Descriptions.Item label="我的邀请码">
                        <Space size={4}>
                          {worker.inviteCode || '-'}
                          {worker.inviteCode ? (
                            <Button
                              size="small"
                              type="link"
                              icon={<CopyOutlined />}
                              onClick={copyInviteCode}
                            />
                          ) : null}
                        </Space>
                      </Descriptions.Item>
                      <Descriptions.Item label="邀请人">
                        {worker.inviter ? worker.inviter.displayName || worker.inviter.username : '-'}
                      </Descriptions.Item>
                      <Descriptions.Item label="已累计完成">
                        {summary?.acceptedOrderCount || 0} 单
                      </Descriptions.Item>
                      <Descriptions.Item label="超时订单">
                        {summary?.timeoutOrderCount || 0} 单
                      </Descriptions.Item>
                      <Descriptions.Item label="累计充值">
                        {formatMoney(worker.wallet.totalCreditedAmount)}
                      </Descriptions.Item>
                      <Descriptions.Item label="提现中金额">
                        {formatMoney(summary?.pendingWithdrawAmount)}
                      </Descriptions.Item>
                      <Descriptions.Item label="免押额度">
                        {formatMoney(worker.level?.permissions.depositFreeAmount || 0)}
                      </Descriptions.Item>
                      <Descriptions.Item label="最大同时接单">
                        {worker.level?.permissions.maxActiveOrders || 0} 单
                      </Descriptions.Item>
                      <Descriptions.Item label="审核备注">
                        {worker.reviewNote || '-'}
                      </Descriptions.Item>
                      <Descriptions.Item label="注册时间">
                        {formatDateTime(worker.createdAt)}
                      </Descriptions.Item>
                      <Descriptions.Item label="最近更新时间">
                        {formatDateTime(worker.updatedAt)}
                      </Descriptions.Item>
                    </Descriptions>
                  </Card>
                ),
              },
              {
                key: 'ledger',
                label: '资金流水',
                children: (
                  <Card
                    size="small"
                    extra={
                      <Space wrap>
                        <Select
                          value={ledgerType}
                          style={{ width: 170 }}
                          options={[
                            { value: '', label: '全部流水' },
                            { value: 'manual_credit', label: '人工充值' },
                            { value: 'withdraw_paid', label: '提现打款' },
                            { value: 'deposit_freeze', label: '冻结押金' },
                            { value: 'deposit_release', label: '释放押金' },
                            { value: 'deposit_pending_unfreeze', label: '押金待解冻' },
                            { value: 'deposit_unfreeze', label: '押金已解冻' },
                            { value: 'deposit_deduction', label: '扣除押金' },
                            { value: 'reward_settlement', label: '结算报酬' },
                          ]}
                          onChange={(nextType) => {
                            setLedgerType(nextType)
                            setLedgerPage(1)
                          }}
                        />
                        <Button
                          icon={<ReloadOutlined />}
                          loading={ledgersQuery.isFetching}
                          onClick={() => ledgersQuery.refetch()}
                        >
                          刷新
                        </Button>
                      </Space>
                    }
                  >
                    <Table<WorkerWalletLedger>
                      rowKey="ledgerId"
                      size="small"
                      loading={ledgersQuery.isLoading}
                      dataSource={ledgersQuery.data?.data.items || []}
                      columns={ledgerColumns}
                      locale={{
                        emptyText: ledgersQuery.error
                          ? ledgersQuery.error instanceof Error
                            ? ledgersQuery.error.message
                            : '读取钱包流水失败'
                          : '暂无钱包流水',
                      }}
                      pagination={{
                        current: ledgersQuery.data?.data.pagination.page || ledgerPage,
                        pageSize: ledgersQuery.data?.data.pagination.pageSize || ledgerPageSize,
                        total: ledgersQuery.data?.data.pagination.total || 0,
                        showSizeChanger: true,
                        pageSizeOptions: [10, 20, 50],
                        showTotal: (total) => `共 ${total} 条`,
                        onChange: (nextPage, nextPageSize) => {
                          setLedgerPage(nextPage)
                          setLedgerPageSize(nextPageSize)
                        },
                      }}
                      scroll={{ x: 920 }}
                    />
                  </Card>
                ),
              },
              {
                key: 'requests',
                label: '申请记录',
                children: (
                  <Card
                    size="small"
                    extra={
                      <Space wrap>
                        <Select
                          value={requestType}
                          style={{ width: 140 }}
                          options={[
                            { value: '', label: '全部类型' },
                            { value: 'recharge', label: '充值申请' },
                            { value: 'withdraw', label: '提现申请' },
                          ]}
                          onChange={(nextType) => {
                            setRequestType(nextType)
                            setRequestPage(1)
                          }}
                        />
                        <Select
                          value={requestStatus}
                          style={{ width: 140 }}
                          options={[
                            { value: '', label: '全部状态' },
                            { value: 'pending', label: '待处理' },
                            { value: 'approved', label: '已通过' },
                            { value: 'rejected', label: '已拒绝' },
                            { value: 'cancelled', label: '已取消' },
                          ]}
                          onChange={(nextStatus) => {
                            setRequestStatus(nextStatus)
                            setRequestPage(1)
                          }}
                        />
                        <Button
                          icon={<ReloadOutlined />}
                          loading={requestsQuery.isFetching}
                          onClick={() => requestsQuery.refetch()}
                        >
                          刷新
                        </Button>
                      </Space>
                    }
                  >
                    <Table<WorkerFinanceRequest>
                      rowKey="requestId"
                      size="small"
                      loading={requestsQuery.isLoading}
                      dataSource={requestsQuery.data?.data.items || []}
                      columns={requestColumns}
                      locale={{
                        emptyText: requestsQuery.error
                          ? requestsQuery.error instanceof Error
                            ? requestsQuery.error.message
                            : '读取申请记录失败'
                          : '暂无申请记录',
                      }}
                      pagination={{
                        current: requestsQuery.data?.data.pagination.page || requestPage,
                        pageSize: requestsQuery.data?.data.pagination.pageSize || requestPageSize,
                        total: requestsQuery.data?.data.pagination.total || 0,
                        showSizeChanger: true,
                        pageSizeOptions: [10, 20, 50],
                        showTotal: (total) => `共 ${total} 条`,
                        onChange: (nextPage, nextPageSize) => {
                          setRequestPage(nextPage)
                          setRequestPageSize(nextPageSize)
                        },
                      }}
                      scroll={{ x: 980 }}
                    />
                  </Card>
                ),
              },
            ]}
          />
        </Space>
      ) : null}

      <Modal
        title="充值申请"
        open={rechargeOpen}
        destroyOnHidden
        confirmLoading={submittingRecharge}
        onCancel={() => {
          setRechargeOpen(false)
          rechargeForm.resetFields()
        }}
        onOk={() => rechargeForm.submit()}
      >
        <Form
          form={rechargeForm}
          layout="vertical"
          initialValues={{ amount: undefined, note: '' }}
          onFinish={submitRecharge}
        >
          <Alert
            showIcon
            type={hasRechargeConfig(financeConfig) ? 'info' : 'warning'}
            message={
              hasRechargeConfig(financeConfig)
                ? '请先按下方收款信息完成转账，再提交充值申请，管理员核对后会手动入账。'
                : '管理员暂未配置完整收款信息，如无法转账请先联系管理员确认。'
            }
          />
          <Space
            direction="vertical"
            size={12}
            className="full-width"
            style={{ marginTop: 16, marginBottom: 16 }}
          >
            {financeConfig?.recharge.qrCodeImage ? (
              <Image
                width={180}
                src={
                  financeConfig.recharge.qrCodeImage.mediumUrl ||
                  financeConfig.recharge.qrCodeImage.url
                }
              />
            ) : null}
            <Descriptions column={1} bordered size="small">
              <Descriptions.Item label="收款通道">
                {financeConfig?.recharge.channelName || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="收款人">
                {financeConfig?.recharge.accountName || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="收款账号">
                {financeConfig?.recharge.accountNo ? (
                  <Typography.Text copyable>
                    {financeConfig.recharge.accountNo}
                  </Typography.Text>
                ) : (
                  '-'
                )}
              </Descriptions.Item>
              <Descriptions.Item label="充值说明">
                {financeConfig?.recharge.instructions || '请转账后填写备注说明，方便管理员核对。'}
              </Descriptions.Item>
            </Descriptions>
          </Space>
          <Form.Item
            label="充值金额"
            name="amount"
            rules={[{ required: true, message: '请输入充值金额' }]}
          >
            <InputNumber min={0.01} step={1} addonAfter="元" className="full-width" />
          </Form.Item>
          <Form.Item
            label="付款时间"
            name="paidAt"
            rules={[{ required: true, message: '请选择付款时间' }]}
          >
            <DatePicker
              showTime
              style={{ width: '100%' }}
              placeholder="选择转账完成时间"
              format="YYYY-MM-DD HH:mm"
            />
          </Form.Item>
          <Form.Item
            label="付款凭证"
            name="proofFiles"
            extra="上传转账成功截图，便于管理员快速核对入账"
          >
            <ImageUpload scene="worker-finance-proof" scope="worker" maxCount={5} />
          </Form.Item>
          <Form.Item label="备注说明" name="note">
            <Input.TextArea
              rows={4}
              placeholder="填写转账备注、支付时间、截图说明等，方便管理员尽快核对。"
            />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="提现申请"
        open={withdrawOpen}
        destroyOnHidden
        confirmLoading={submittingWithdraw}
        onCancel={() => {
          setWithdrawOpen(false)
          withdrawForm.resetFields()
        }}
        onOk={() => withdrawForm.submit()}
      >
        <Form
          form={withdrawForm}
          layout="vertical"
          initialValues={{ accountChannel: 'alipay' }}
          onFinish={submitWithdraw}
        >
          {financeConfig?.withdraw.instructions ? (
            <Alert
              showIcon
              type="info"
              message={financeConfig.withdraw.instructions}
              style={{ marginBottom: 16 }}
            />
          ) : null}
          <Alert
            showIcon
            type="warning"
            message={`每天限提现 1 次；有押金的工单验收通过后，押金需 ${Number(
              financeConfig?.depositUnfreezeDays ?? 3,
            )} 天解冻到账后方可提现。`}
            style={{ marginBottom: 16 }}
          />
          <Form.Item label="可提现余额">
            <Typography.Text strong>
              {formatMoney(resolveAvailableForWithdraw(worker, summary))}
            </Typography.Text>
          </Form.Item>
          <Form.Item
            label="提现金额"
            name="amount"
            rules={[{ required: true, message: '请输入提现金额' }]}
          >
            <InputNumber min={0.01} step={1} addonAfter="元" className="full-width" />
          </Form.Item>
          <Form.Item
            label="提现方式"
            name="accountChannel"
            rules={[{ required: true, message: '请选择提现方式' }]}
          >
            <Select
              options={[
                { value: 'alipay', label: '支付宝' },
                { value: 'wechat', label: '微信收款' },
                { value: 'bank', label: '银行卡' },
              ]}
            />
          </Form.Item>
          <Form.Item
            label="收款人姓名"
            name="accountName"
            rules={[{ required: true, message: '请输入收款人姓名' }]}
          >
            <Input placeholder="请输入真实姓名" />
          </Form.Item>
          <Form.Item
            label="收款账号"
            name="accountNo"
            rules={[{ required: true, message: '请输入收款账号' }]}
          >
            <Input placeholder="请输入支付宝账号、微信号或银行卡号" />
          </Form.Item>
          <Form.Item label="备注说明" name="note">
            <Input.TextArea
              rows={4}
              placeholder="可补充到账要求、手机号、开户行等说明。"
            />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="修改密码"
        open={passwordOpen}
        destroyOnHidden
        confirmLoading={submittingPassword}
        onCancel={() => {
          setPasswordOpen(false)
          passwordForm.resetFields()
        }}
        onOk={() => passwordForm.submit()}
      >
        <Form form={passwordForm} layout="vertical" onFinish={submitPasswordChange}>
          <Form.Item
            label="当前密码"
            name="currentPassword"
            rules={[{ required: true, message: '请输入当前密码' }]}
          >
            <Input.Password autoComplete="current-password" />
          </Form.Item>
          <Form.Item
            label="新密码"
            name="newPassword"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '新密码至少 6 位' },
            ]}
          >
            <Input.Password autoComplete="new-password" />
          </Form.Item>
          <Form.Item
            label="确认新密码"
            name="confirmPassword"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: '请再次输入新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || value === getFieldValue('newPassword')) {
                    return Promise.resolve()
                  }
                  return Promise.reject(new Error('两次输入的新密码不一致'))
                },
              }),
            ]}
          >
            <Input.Password autoComplete="new-password" />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="联系管理员"
        open={contactOpen}
        destroyOnHidden
        footer={
          <Button type="primary" onClick={() => setContactOpen(false)}>
            我知道了
          </Button>
        }
        onCancel={() => setContactOpen(false)}
      >
        <Space direction="vertical" size={16} className="full-width">
          <Alert
            showIcon
            type="info"
            message="充值、提现与审核问题目前都由后台管理员人工处理。提交申请后，如需加急，可把下方账号信息发给管理员。"
          />
          <Descriptions column={1} bordered size="small">
            <Descriptions.Item label="账号">
              <Typography.Text copyable>{worker?.username || '-'}</Typography.Text>
            </Descriptions.Item>
            <Descriptions.Item label="昵称">
              {worker?.displayName || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="手机号">
              <Typography.Text copyable>{worker?.phone || '-'}</Typography.Text>
            </Descriptions.Item>
            <Descriptions.Item label="审核状态">
              {formatWorkerStatus(worker?.status || '')}
            </Descriptions.Item>
            <Descriptions.Item label="当前余额">
              {formatMoney(worker?.wallet.availableAmount)}
            </Descriptions.Item>
          </Descriptions>
          <Typography.Paragraph className="worker-profile-help-text">
            建议沟通时一起提供：申请类型、金额、订单号或转账备注、收款方式，以及当前账号信息。
          </Typography.Paragraph>
        </Space>
      </Modal>
    </section>
  )
}

function resolveAvailableForWithdraw(
  worker: WorkerUser | undefined,
  summary: WorkerProfileSummary | undefined,
) {
  return Math.max(
    0,
    Number(worker?.wallet.availableAmount || 0) -
      Number(summary?.pendingWithdrawAmount || 0),
  )
}

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

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

function formatWorkerStatus(status: string) {
  if (status === 'active') return '已审核'
  if (status === 'pending_review') return '待审核'
  if (status === 'rejected') return '审核未通过'
  if (status === 'disabled') return '已停用'
  return status || '-'
}

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'
}

function formatLedgerType(ledgerType: string) {
  const labels: Record<string, string> = {
    manual_credit: '人工充值',
    withdraw_paid: '提现打款',
    deposit_freeze: '冻结押金',
    deposit_release: '释放押金',
    deposit_pending_unfreeze: '押金待解冻',
    deposit_unfreeze: '押金已解冻',
    deposit_deduction: '扣除押金',
    reward_settlement: '结算报酬',
  }
  return labels[ledgerType] || ledgerType || '-'
}

function resolveLedgerTagColor(ledgerType: string) {
  if (ledgerType === 'manual_credit') return 'blue'
  if (ledgerType === 'withdraw_paid') return 'purple'
  if (ledgerType === 'deposit_freeze') return 'gold'
  if (ledgerType === 'deposit_release') return 'green'
  if (ledgerType === 'deposit_pending_unfreeze') return 'orange'
  if (ledgerType === 'deposit_unfreeze') return 'green'
  if (ledgerType === 'deposit_deduction') return 'red'
  if (ledgerType === 'reward_settlement') return 'cyan'
  return 'default'
}

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

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

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

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>
  )
}

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 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'
}

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

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)}`
}

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