import { ReloadOutlined } from '@ant-design/icons'
import { Button, Card, Empty, Pagination, Select, Space, Spin, Table, Tag } from 'antd'

import type {
  WorkerFinanceRequest,
  WorkerListResponse,
  WorkerWalletLedger,
} from '@/types/worker-platform'
import type { ApiEnvelope } from '@/lib/http'
import { formatDateTime } from '@/utils/date-time'

import {
  formatLedgerType,
  formatMoney,
  formatRequestStatus,
  formatRequestType,
  formatWithdrawChannel,
  maskAccountNo,
  renderRechargeRequestSummary,
  resolveLedgerFrozenAmountLabel,
  resolveLedgerTagColor,
  resolveRequestStatusColor,
  workerFinanceRequestColumns,
  workerLedgerColumns,
} from './worker-profile-view-utils'

const LEDGER_TYPE_OPTIONS = [
  { value: '', label: '全部流水' },
  { value: 'manual_credit', label: '人工充值' },
  { value: 'withdraw_freeze', label: '提现冻结' },
  { value: 'withdraw_paid', label: '提现打款' },
  { value: 'withdraw_release', label: '提现退回' },
  { value: 'deposit_freeze', label: '冻结押金' },
  { value: 'deposit_release', label: '释放押金' },
  { value: 'deposit_pending_unfreeze', label: '待解冻金额' },
  { value: 'reward_pending_unfreeze', label: '报酬待解冻' },
  { value: 'deposit_unfreeze', label: '押金已解冻' },
  { value: 'deposit_deduction', label: '扣除押金' },
  { value: 'reward_settlement', label: '结算报酬' },
  { value: 'sharing_reward', label: '拼单报酬' },
  { value: 'after_sales_deposit_deduction', label: '售后扣减押金' },
  { value: 'after_sales_balance_deduction', label: '售后扣减余额' },
  { value: 'after_sales_debt_offset', label: '抵扣售后欠款' },
  { value: 'after_sales_refund', label: '售后追缴退还' },
]

const REQUEST_TYPE_OPTIONS = [
  { value: '', label: '全部类型' },
  { value: 'recharge', label: '充值申请' },
  { value: 'withdraw', label: '提现申请' },
]

const REQUEST_STATUS_OPTIONS = [
  { value: '', label: '全部状态' },
  { value: 'pending', label: '待处理' },
  { value: 'approved', label: '已通过' },
  { value: 'rejected', label: '已驳回' },
]

type LedgerRecordsProps = {
  data: ApiEnvelope<WorkerListResponse<WorkerWalletLedger>> | undefined
  error: unknown
  loading: boolean
  refreshing: boolean
  ledgerType: string
  onLedgerTypeChange: (ledgerType: string) => void
  onReload: () => void
  page: number
  pageSize: number
  onPageChange: (page: number, pageSize: number) => void
}

type RequestRecordsProps = {
  data: ApiEnvelope<WorkerListResponse<WorkerFinanceRequest>> | undefined
  error: unknown
  loading: boolean
  refreshing: boolean
  requestType: string
  requestStatus: string
  onRequestTypeChange: (requestType: string) => void
  onRequestStatusChange: (requestStatus: string) => void
  onReload: () => void
  page: number
  pageSize: number
  onPageChange: (page: number, pageSize: number) => void
}

export function WorkerProfileMobileLedgerRecords({
  data,
  loading,
  refreshing,
  ledgerType,
  onLedgerTypeChange,
  onReload,
  page,
  pageSize,
  onPageChange,
}: LedgerRecordsProps) {
  const items = data?.data.items || []
  const pagination = data?.data.pagination
  return (
    <div className="worker-profile-mobile-tab-pane">
      <div className="worker-profile-mobile-filter-row">
        <Select
          size="small"
          value={ledgerType}
          style={{ width: 140 }}
          options={LEDGER_TYPE_OPTIONS}
          onChange={onLedgerTypeChange}
        />
        <Button size="small" icon={<ReloadOutlined />} loading={refreshing} onClick={onReload}>
          刷新
        </Button>
      </div>
      <div className="worker-profile-mobile-records">
        {loading ? (
          <div className="worker-hall-loading">
            <Spin size="large" />
          </div>
        ) : items.length === 0 ? (
          <Empty description="暂无钱包流水" />
        ) : (
          items.map((row) => (
            <div key={row.ledgerId} className="worker-profile-record-card">
              <div className="worker-profile-record-row-head">
                <Tag color={resolveLedgerTagColor(row.ledgerType)}>
                  {formatLedgerType(row.ledgerType)}
                </Tag>
                <strong
                  className={row.amount >= 0 ? 'worker-amount-positive' : 'worker-amount-negative'}
                  style={{ fontSize: 16 }}
                >
                  {row.amount >= 0 ? '+' : ''}
                  {formatMoney(row.amount)}
                </strong>
              </div>
              <div className="worker-profile-record-row-meta">
                <span>变动后余额: {formatMoney(row.balanceAfter)}</span>
                <span>
                  {resolveLedgerFrozenAmountLabel(row.ledgerType)}: {formatMoney(row.frozenAfter)}
                </span>
              </div>
              {row.note ? <div className="worker-profile-record-note">说明: {row.note}</div> : null}
              {row.relatedPlatformOrderId ? (
                <div className="worker-profile-record-sub">订单号 {row.relatedPlatformOrderId}</div>
              ) : null}
              <div className="worker-profile-record-time">
                {formatDateTime(String(row.createdAt || ''))}
              </div>
            </div>
          ))
        )}
        {(pagination?.total || 0) > 0 ? (
          <div className="worker-orders-mobile-pagination">
            <Pagination
              current={pagination?.page || page}
              pageSize={pagination?.pageSize || pageSize}
              total={pagination?.total || 0}
              simple
              onChange={onPageChange}
            />
          </div>
        ) : null}
      </div>
    </div>
  )
}

export function WorkerProfileMobileRequestRecords({
  data,
  loading,
  refreshing,
  requestType,
  requestStatus,
  onRequestTypeChange,
  onRequestStatusChange,
  onReload,
  page,
  pageSize,
  onPageChange,
}: RequestRecordsProps) {
  const items = data?.data.items || []
  const pagination = data?.data.pagination
  return (
    <div className="worker-profile-mobile-tab-pane">
      <div className="worker-profile-mobile-filter-row">
        <Space size={6} wrap>
          <Select
            size="small"
            value={requestType}
            style={{ width: 110 }}
            options={REQUEST_TYPE_OPTIONS}
            onChange={onRequestTypeChange}
          />
          <Select
            size="small"
            value={requestStatus}
            style={{ width: 110 }}
            options={REQUEST_STATUS_OPTIONS}
            onChange={onRequestStatusChange}
          />
          <Button size="small" icon={<ReloadOutlined />} loading={refreshing} onClick={onReload} />
        </Space>
      </div>
      <div className="worker-profile-mobile-records">
        {loading ? (
          <div className="worker-hall-loading">
            <Spin size="large" />
          </div>
        ) : items.length === 0 ? (
          <Empty description="暂无申请记录" />
        ) : (
          items.map((row) => (
            <div key={row.requestId} className="worker-profile-record-card">
              <div className="worker-profile-record-row-head">
                <Space size={4}>
                  <Tag color={row.requestType === 'withdraw' ? 'green' : 'blue'}>
                    {formatRequestType(row.requestType)}
                  </Tag>
                  <Tag color={resolveRequestStatusColor(row.status)}>
                    {formatRequestStatus(row.status)}
                  </Tag>
                </Space>
                <strong style={{ fontSize: 16 }}>{formatMoney(row.amount)}</strong>
              </div>
              {row.requestType === 'withdraw' ? (
                <div className="worker-profile-record-row-meta">
                  收款: {formatWithdrawChannel(row.accountChannel)} / {row.accountName || '-'} (
                  {maskAccountNo(row.accountNo)})
                </div>
              ) : (
                <div className="worker-profile-record-row-meta">
                  {renderRechargeRequestSummary(row)}
                </div>
              )}
              {row.note ? <div className="worker-profile-record-note">备注: {row.note}</div> : null}
              {row.reviewedNote ? (
                <div className="worker-profile-record-note" style={{ color: '#d97706' }}>
                  审核备注: {row.reviewedNote}
                </div>
              ) : null}
              <div className="worker-profile-record-time">
                {formatDateTime(String(row.createdAt || ''))}
              </div>
            </div>
          ))
        )}
        {(pagination?.total || 0) > 0 ? (
          <div className="worker-orders-mobile-pagination">
            <Pagination
              current={pagination?.page || page}
              pageSize={pagination?.pageSize || pageSize}
              total={pagination?.total || 0}
              simple
              onChange={onPageChange}
            />
          </div>
        ) : null}
      </div>
    </div>
  )
}

export function WorkerProfileDesktopLedgerRecords({
  data,
  error,
  loading,
  refreshing,
  ledgerType,
  onLedgerTypeChange,
  onReload,
  page,
  pageSize,
  onPageChange,
}: LedgerRecordsProps) {
  const pagination = data?.data.pagination
  return (
    <Card
      size="small"
      extra={
        <Space wrap>
          <Select
            value={ledgerType}
            style={{ width: 170 }}
            options={LEDGER_TYPE_OPTIONS}
            onChange={onLedgerTypeChange}
          />
          <Button icon={<ReloadOutlined />} loading={refreshing} onClick={onReload}>
            刷新
          </Button>
        </Space>
      }
    >
      <Table<WorkerWalletLedger>
        rowKey="ledgerId"
        size="small"
        loading={loading}
        dataSource={data?.data.items || []}
        columns={workerLedgerColumns}
        locale={{ emptyText: resolveEmptyText(error, '读取资金流水失败', '暂无钱包流水') }}
        pagination={{
          current: pagination?.page || page,
          pageSize: pagination?.pageSize || pageSize,
          total: pagination?.total || 0,
          showSizeChanger: true,
          pageSizeOptions: [10, 20, 50],
          showTotal: (total) => `共 ${total} 条`,
          onChange: onPageChange,
        }}
        scroll={{ x: 980 }}
      />
    </Card>
  )
}

export function WorkerProfileDesktopRequestRecords({
  data,
  error,
  loading,
  refreshing,
  requestType,
  requestStatus,
  onRequestTypeChange,
  onRequestStatusChange,
  onReload,
  page,
  pageSize,
  onPageChange,
}: RequestRecordsProps) {
  const pagination = data?.data.pagination
  return (
    <Card
      size="small"
      extra={
        <Space wrap>
          <Select
            value={requestType}
            style={{ width: 140 }}
            options={REQUEST_TYPE_OPTIONS}
            onChange={onRequestTypeChange}
          />
          <Select
            value={requestStatus}
            style={{ width: 140 }}
            options={REQUEST_STATUS_OPTIONS}
            onChange={onRequestStatusChange}
          />
          <Button icon={<ReloadOutlined />} loading={refreshing} onClick={onReload}>
            刷新
          </Button>
        </Space>
      }
    >
      <Table<WorkerFinanceRequest>
        rowKey="requestId"
        size="small"
        loading={loading}
        dataSource={data?.data.items || []}
        columns={workerFinanceRequestColumns}
        locale={{ emptyText: resolveEmptyText(error, '读取申请记录失败', '暂无申请记录') }}
        pagination={{
          current: pagination?.page || page,
          pageSize: pagination?.pageSize || pageSize,
          total: pagination?.total || 0,
          showSizeChanger: true,
          pageSizeOptions: [10, 20, 50],
          showTotal: (total) => `共 ${total} 条`,
          onChange: onPageChange,
        }}
        scroll={{ x: 980 }}
      />
    </Card>
  )
}

function resolveEmptyText(error: unknown, fallback: string, emptyText: string) {
  if (!error) return emptyText
  return error instanceof Error ? error.message : fallback
}
