import {
  BankOutlined,
  CopyOutlined,
  CustomerServiceOutlined,
  GlobalOutlined,
  LockOutlined,
  LogoutOutlined,
  ReloadOutlined,
  UserSwitchOutlined,
  WalletOutlined,
} from '@ant-design/icons'
import { Alert, Avatar, Button, Progress, Tag } from 'antd'
import type { ReactNode } from 'react'

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

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

type WorkerProfileMobileViewProps = {
  worker: WorkerUser
  summary: WorkerProfileSummary | undefined
  levelProgress: WorkerLevelProgress | null | undefined
  canUseFinanceActions: boolean
  needsAlipayQrCode: boolean
  activeTab: string
  loading: boolean
  ledgerRecords: ReactNode
  requestRecords: ReactNode
  onActiveTabChange: (tab: string) => void
  onRefresh: () => void
  onCopyInviteCode: () => void
  onRecharge: () => void
  onWithdraw: () => void
  onChangePassword: () => void
  onRename: () => void
  renameDisabled: boolean
  onManageDevices: () => void
  onContact: () => void
  onAddAlipayQrCode: () => void
  onLogout: () => void
}

export function WorkerProfileMobileView({
  worker,
  summary,
  levelProgress,
  canUseFinanceActions,
  needsAlipayQrCode,
  activeTab,
  loading,
  ledgerRecords,
  requestRecords,
  onActiveTabChange,
  onRefresh,
  onCopyInviteCode,
  onRecharge,
  onWithdraw,
  onChangePassword,
  onRename,
  renameDisabled,
  onManageDevices,
  onContact,
  onAddAlipayQrCode,
  onLogout,
}: WorkerProfileMobileViewProps) {
  return (
    <div className="worker-profile-mobile-page">
      <div className="worker-profile-mobile-hero">
        <div className="worker-profile-mobile-user-row">
          <Avatar size={52} className="worker-profile-mobile-avatar">
            {resolveWorkerInitial(worker)}
          </Avatar>
          <div className="worker-profile-mobile-user-info">
            <div className="worker-profile-mobile-name-row">
              <strong className="worker-profile-mobile-name">
                {worker.displayName || worker.username}
              </strong>
            </div>
            <div className="worker-profile-mobile-tags-row">
              <span className="worker-profile-mobile-vip-badge">
                {worker.level?.name || '未分级'}
              </span>
              <Tag
                color={resolveWorkerStatusColor(worker.status)}
                className="worker-profile-mobile-tag"
              >
                {formatWorkerStatus(worker.status)}
              </Tag>
              <Tag className="worker-profile-mobile-tag">
                {worker.workerType === 'internal' ? '内部打手' : '外部打手'}
              </Tag>
            </div>
            <div className="worker-profile-mobile-account-text">
              账号: {worker.username} {worker.phone ? `· ${worker.phone}` : ''}
            </div>
          </div>
          <Button
            type="text"
            shape="circle"
            icon={<ReloadOutlined />}
            className="worker-profile-mobile-refresh-btn"
            loading={loading}
            onClick={onRefresh}
          />
        </div>

        <div className="worker-profile-mobile-hero-bottom">
          <div className="worker-profile-mobile-invite-bar">
            <span className="worker-profile-mobile-invite-label">我的邀请码:</span>
            <strong className="worker-profile-mobile-invite-code">
              {worker.inviteCode || '-'}
            </strong>
            {worker.inviteCode ? (
              <button
                type="button"
                className="worker-profile-mobile-copy-btn"
                onClick={onCopyInviteCode}
              >
                <CopyOutlined /> 复制
              </button>
            ) : null}
          </div>

          {levelProgress && levelProgress.nextThreshold !== null ? (
            <div className="worker-profile-mobile-level-box">
              <div className="worker-profile-mobile-level-text">
                已完成 {summary?.acceptedOrderCount || 0} 单 · 距下一级还需{' '}
                {Math.max(0, levelProgress.nextThreshold - (summary?.acceptedOrderCount || 0))} 单
              </div>
              <Progress
                percent={levelProgress.progressPercent}
                size="small"
                strokeColor={{ '0%': '#f97316', '100%': '#fbbf24' }}
                showInfo={false}
              />
            </div>
          ) : (
            <div className="worker-profile-mobile-level-text">
              已完成 {summary?.acceptedOrderCount || 0} 单 · 当前已是最高等级
            </div>
          )}
        </div>
      </div>

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

      <div className="worker-profile-mobile-wallet-card">
        <div className="worker-profile-mobile-wallet-top">
          <div className="worker-profile-mobile-wallet-main">
            <span className="worker-profile-mobile-wallet-title">可用余额</span>
            <strong className="worker-profile-mobile-wallet-amount">
              {formatMoney(worker.wallet.availableAmount)}
            </strong>
          </div>
          <div className="worker-profile-mobile-wallet-actions">
            <Button
              type="primary"
              size="middle"
              icon={<WalletOutlined />}
              disabled={!canUseFinanceActions}
              className="worker-profile-mobile-recharge-btn"
              onClick={onRecharge}
            >
              充值
            </Button>
            <Button
              size="middle"
              icon={<BankOutlined />}
              disabled={!canUseFinanceActions}
              className="worker-profile-mobile-withdraw-btn"
              onClick={onWithdraw}
            >
              提现
            </Button>
          </div>
        </div>

        <div className="worker-profile-mobile-wallet-grid">
          <MobileWalletItem label="冻结押金" amount={worker.wallet.frozenDepositAmount} />
          <MobileWalletItem label="待解冻金额" amount={worker.wallet.pendingUnfreezeAmount} />
          <MobileWalletItem label="累计结算" amount={worker.wallet.totalSettledAmount} />
        </div>
      </div>

      <div className="worker-profile-mobile-tools-card">
        <MobileTool
          label="修改昵称"
          icon={<UserSwitchOutlined />}
          color="#4338ca"
          background="#eef2ff"
          disabled={renameDisabled}
          onClick={onRename}
        />
        <MobileTool
          label="修改密码"
          icon={<LockOutlined />}
          color="#3b82f6"
          background="#eff6ff"
          onClick={onChangePassword}
        />
        <MobileTool
          label="登录设备"
          icon={<GlobalOutlined />}
          color="#0f766e"
          background="#f0fdfa"
          onClick={onManageDevices}
        />
        <MobileTool
          label="联系客服"
          icon={<CustomerServiceOutlined />}
          color="#16a34a"
          background="#f0fdf4"
          onClick={onContact}
        />
        <MobileTool
          label="邀请好友"
          icon={<CopyOutlined />}
          color="#d97706"
          background="#fef3c7"
          disabled={!worker.inviteCode}
          onClick={onCopyInviteCode}
        />
        {needsAlipayQrCode ? (
          <MobileTool
            label="补充支付宝收款码"
            icon={<BankOutlined />}
            color="#7c3aed"
            background="#f5f3ff"
            disabled={!canUseFinanceActions}
            onClick={onAddAlipayQrCode}
          />
        ) : null}
        <MobileTool
          label="退出登录"
          icon={<LogoutOutlined />}
          color="#ef4444"
          background="#fef2f2"
          onClick={onLogout}
        />
      </div>

      <div className="worker-profile-mobile-sections-card">
        <div className="worker-profile-mobile-tab-nav">
          <MobileTab
            active={activeTab === 'ledger'}
            label="资金流水"
            onClick={() => onActiveTabChange('ledger')}
          />
          <MobileTab
            active={activeTab === 'requests'}
            label="申请记录"
            onClick={() => onActiveTabChange('requests')}
          />
          <MobileTab
            active={activeTab === 'account'}
            label="账号详情"
            onClick={() => onActiveTabChange('account')}
          />
        </div>

        <div className="worker-profile-mobile-tab-body">
          {activeTab === 'ledger' ? ledgerRecords : null}
          {activeTab === 'requests' ? requestRecords : null}
          {activeTab === 'account' ? (
            <WorkerProfileMobileAccountDetails worker={worker} summary={summary} />
          ) : null}
        </div>
      </div>
    </div>
  )
}

function MobileWalletItem({ label, amount }: { label: string; amount: number }) {
  return (
    <div className="worker-profile-mobile-wallet-col">
      <span className="worker-profile-mobile-sub-label">{label}</span>
      <strong className="worker-profile-mobile-sub-val">{formatMoney(amount)}</strong>
    </div>
  )
}

function MobileTool({
  label,
  icon,
  color,
  background,
  disabled = false,
  onClick,
}: {
  label: string
  icon: ReactNode
  color: string
  background: string
  disabled?: boolean
  onClick: () => void
}) {
  return (
    <button
      type="button"
      className="worker-profile-mobile-tool-item"
      disabled={disabled}
      onClick={onClick}
    >
      <div className="worker-profile-mobile-tool-icon" style={{ background, color }}>
        {icon}
      </div>
      <span>{label}</span>
    </button>
  )
}

function MobileTab({
  active,
  label,
  onClick,
}: {
  active: boolean
  label: string
  onClick: () => void
}) {
  return (
    <button
      type="button"
      className={`worker-profile-mobile-tab-btn ${active ? 'active' : ''}`}
      onClick={onClick}
    >
      {label}
    </button>
  )
}

function WorkerProfileMobileAccountDetails({
  worker,
  summary,
}: {
  worker: WorkerUser
  summary: WorkerProfileSummary | undefined
}) {
  const items: Array<[string, ReactNode]> = [
    ['账号', worker.username],
    ['昵称', worker.displayName || '-'],
    ['手机号', worker.phone || '-'],
    [
      '账号状态',
      <Tag key="worker-status" color={resolveWorkerStatusColor(worker.status)}>
        {formatWorkerStatus(worker.status)}
      </Tag>,
    ],
    ['当前等级', worker.level?.name || '-'],
    ['免押额度', formatMoney(worker.effectiveDepositFreeAmount)],
    ['最大同时接单', `${worker.level?.permissions.maxActiveOrders || 0} 单`],
    ['邀请人', worker.inviter ? worker.inviter.displayName || worker.inviter.username : '-'],
    ['已完成订单', `${summary?.acceptedOrderCount || 0} 单`],
    ['累计充值', formatMoney(worker.wallet.totalCreditedAmount)],
    ['注册时间', formatDateTime(worker.createdAt)],
  ]

  return (
    <div className="worker-profile-mobile-tab-pane">
      <div className="worker-profile-mobile-account-list">
        {items.map(([label, value]) => (
          <div key={label} className="worker-profile-mobile-account-item">
            <span className="worker-profile-mobile-acc-label">{label}</span>
            <span className="worker-profile-mobile-acc-val">{value}</span>
          </div>
        ))}
      </div>
    </div>
  )
}
