import {
  BankOutlined,
  CopyOutlined,
  CustomerServiceOutlined,
  GlobalOutlined,
  LockOutlined,
  LogoutOutlined,
  UserOutlined,
  WalletOutlined,
} from '@ant-design/icons'
import { Avatar, Button, Card, Descriptions, Progress, Space, Tag, Tooltip, Typography } from 'antd'

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

import {
  formatMoney,
  formatWorkerStatus,
  formatWithdrawChannel,
  resolveWorkerInitial,
  resolveWorkerStatusColor,
} from './worker-profile-view-utils'

export function WorkerProfileDesktopIdentity({
  worker,
  summary,
  levelProgress,
  onCopyInviteCode,
}: {
  worker: WorkerUser
  summary: WorkerProfileSummary | undefined
  levelProgress: WorkerLevelProgress | null | undefined
  onCopyInviteCode: () => void
}) {
  return (
    <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 color={worker.workerType === 'internal' ? 'blue' : 'default'}>
            {worker.workerType === 'internal' ? '内部打手' : '外部打手'}
          </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={onCopyInviteCode}
          >
            复制
          </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>
  )
}

export function WorkerProfileDesktopWallet({ worker }: { worker: WorkerUser }) {
  const items = [
    ['可用余额', worker.wallet.availableAmount, '可用于抢单冻结或提现申请'],
    ['冻结押金', worker.wallet.frozenDepositAmount, '抢单后冻结，验收后进入待解冻'],
    [
      '待解冻金额',
      worker.wallet.pendingUnfreezeAmount,
      '验收报酬与押金按配置天数解冻到账，期间不可提现',
    ],
    ['累计结算', worker.wallet.totalSettledAmount, '已结算入账的报酬合计'],
  ] as const
  return (
    <Card size="small" className="worker-profile-wallet-card">
      <div className="worker-profile-wallet-strip">
        {items.map(([label, amount, note]) => (
          <div key={label} className="worker-profile-wallet-item">
            <span className="worker-profile-wallet-label">{label}</span>
            <strong className="worker-profile-wallet-value">{formatMoney(amount)}</strong>
            <small className="worker-profile-wallet-note">{note}</small>
          </div>
        ))}
      </div>
    </Card>
  )
}

export function WorkerProfileDesktopActions({
  canUseFinanceActions,
  canAddWithdrawalAccount,
  needsAlipayQrCode,
  onRecharge,
  onWithdraw,
  onAddWithdrawalAccount,
  onAddAlipayQrCode,
  onChangePassword,
  onRename,
  renameDisabled,
  renameHint,
  onManageDevices,
  onContact,
  onLogout,
}: {
  canUseFinanceActions: boolean
  canAddWithdrawalAccount: boolean
  needsAlipayQrCode: boolean
  onRecharge: () => void
  onWithdraw: () => void
  onAddWithdrawalAccount: () => void
  onAddAlipayQrCode: () => void
  onChangePassword: () => void
  onRename: () => void
  renameDisabled: boolean
  renameHint: string
  onManageDevices: () => void
  onContact: () => void
  onLogout: () => void
}) {
  return (
    <Card title="快捷操作" size="small">
      <Space wrap size={[12, 12]}>
        <Button
          type="primary"
          icon={<WalletOutlined />}
          disabled={!canUseFinanceActions}
          onClick={onRecharge}
        >
          充值申请
        </Button>
        <Button
          type="primary"
          icon={<BankOutlined />}
          disabled={!canUseFinanceActions}
          onClick={onWithdraw}
        >
          提现申请
        </Button>
        {canAddWithdrawalAccount ? (
          <Button
            icon={<BankOutlined />}
            disabled={!canUseFinanceActions}
            onClick={onAddWithdrawalAccount}
          >
            添加提现信息
          </Button>
        ) : null}
        {needsAlipayQrCode ? (
          <Button
            icon={<BankOutlined />}
            disabled={!canUseFinanceActions}
            onClick={onAddAlipayQrCode}
          >
            补充支付宝收款码
          </Button>
        ) : null}
        <Tooltip title={renameHint}>
          <Button icon={<UserOutlined />} disabled={renameDisabled} onClick={onRename}>
            修改昵称
          </Button>
        </Tooltip>
        <Button icon={<LockOutlined />} onClick={onChangePassword}>
          修改密码
        </Button>
        <Button icon={<GlobalOutlined />} onClick={onManageDevices}>
          登录设备
        </Button>
        <Button icon={<CustomerServiceOutlined />} onClick={onContact}>
          联系管理员
        </Button>
        <Button danger icon={<LogoutOutlined />} onClick={onLogout}>
          退出登录
        </Button>
      </Space>
    </Card>
  )
}

export function WorkerProfileDesktopAccountDetails({
  worker,
  summary,
  withdrawalAccounts,
  canUseFinanceActions,
  onCopyInviteCode,
  onAddWithdrawalAccount,
}: {
  worker: WorkerUser
  summary: WorkerProfileSummary | undefined
  withdrawalAccounts: WorkerWithdrawalAccount[]
  canUseFinanceActions: boolean
  onCopyInviteCode: () => void
  onAddWithdrawalAccount: () => void
}) {
  return (
    <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={onCopyInviteCode} />
            ) : 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="提现信息" span={2}>
          {withdrawalAccounts.length > 0 ? (
            <Space direction="vertical" size={2}>
              {withdrawalAccounts.map((account) => (
                <Space key={account.accountChannel} wrap size={4}>
                  <Typography.Text>{formatWithdrawChannel(account.accountChannel)}</Typography.Text>
                  <Typography.Text>{account.accountName}</Typography.Text>
                  <Typography.Text type="secondary">
                    {account.accountChannel === 'wechat'
                      ? '已上传收款二维码'
                      : `${account.accountNoMasked} / ${account.alipayQrCodeImage ? '已上传收款二维码' : '未上传收款二维码'}`}
                  </Typography.Text>
                  <Typography.Text type="secondary">收款人姓名和账号已锁定</Typography.Text>
                </Space>
              ))}
            </Space>
          ) : (
            <Button
              type="link"
              size="small"
              disabled={!canUseFinanceActions}
              onClick={onAddWithdrawalAccount}
            >
              添加提现信息
            </Button>
          )}
        </Descriptions.Item>
        <Descriptions.Item label="免押额度">
          {formatMoney(worker.effectiveDepositFreeAmount)}
        </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>
  )
}
