'use client';

import { useState } from 'react';
import { useWalletLedger } from '../hooks/use-users';
import { formatDecimal, formatNumber } from '@/lib/utils/format';
import { formatDateTime } from '@/lib/utils/date';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Skeleton } from '@/components/ui/skeleton';
import { ChevronLeft, ChevronRight, Wallet, TrendingUp, TrendingDown } from 'lucide-react';
import { cn } from '@/lib/utils';

interface WalletLedgerProps {
  accountSequence: string;
}

// 流水类型标签
const entryTypeLabels: Record<string, string> = {
  DEPOSIT: '充值',
  DEPOSIT_USDT: 'USDT充值',
  DEPOSIT_BNB: 'BNB充值',
  WITHDRAW: '提现',
  WITHDRAW_FROZEN: '提现冻结',
  WITHDRAW_CONFIRMED: '提现确认',
  WITHDRAW_CANCELLED: '提现取消',
  PLANTING_PAYMENT: '认种支付',
  PLANTING_FROZEN: '认种冻结',
  PLANTING_DEDUCT: '认种扣款',
  REWARD_PENDING: '收益待领取',
  REWARD_SETTLED: '收益结算',
  REWARD_EXPIRED: '收益过期',
  TRANSFER_OUT: '转出',
  TRANSFER_IN: '转入',
  INTERNAL_TRANSFER: '内部转账',
  ADMIN_ADJUSTMENT: '管理员调整',
  SYSTEM_DEDUCT: '系统扣款',
  FEE: '手续费',
  MINING_REWARD: '挖矿奖励',
  TRADE_BUY: '买入',
  TRADE_SELL: '卖出',
};

// 资产类型标签
const assetTypeLabels: Record<string, string> = {
  USDT: '绿积分',
  DST: 'DST',
  BNB: 'BNB',
  OG: 'OG',
  RWAD: 'RWAD',
  HASHPOWER: '算力',
  MINING: '挖矿积分',
  TRADING: '交易积分',
};

export function WalletLedger({ accountSequence }: WalletLedgerProps) {
  const [page, setPage] = useState(1);
  const pageSize = 10;

  const { data, isLoading } = useWalletLedger(accountSequence, { page, pageSize });

  if (isLoading) {
    return (
      <div className="space-y-6">
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">钱包汇总</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
              {[...Array(6)].map((_, i) => (
                <Skeleton key={i} className="h-16 w-full" />
              ))}
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-0">
            <Skeleton className="h-64 w-full" />
          </CardContent>
        </Card>
      </div>
    );
  }

  if (!data) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">钱包信息</CardTitle>
        </CardHeader>
        <CardContent>
          <p className="text-muted-foreground text-center py-8">暂无钱包数据</p>
        </CardContent>
      </Card>
    );
  }

  return (
    <div className="space-y-6">
      {/* 钱包汇总 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg flex items-center gap-2">
            <Wallet className="h-5 w-5 text-blue-600" />
            钱包汇总
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
            <div className="text-center p-4 bg-muted rounded-lg">
              <p className="text-sm text-muted-foreground">绿积分 可用</p>
              <p className="text-2xl font-bold text-green-600 font-mono">
                {formatDecimal(data.summary.usdtAvailable, 8)}
              </p>
            </div>
            <div className="text-center p-4 bg-muted rounded-lg">
              <p className="text-sm text-muted-foreground">绿积分 冻结</p>
              <p className="text-2xl font-bold text-orange-600 font-mono">
                {formatDecimal(data.summary.usdtFrozen, 8)}
              </p>
            </div>
            <div className="text-center p-4 bg-muted rounded-lg">
              <p className="text-sm text-muted-foreground">待领取收益</p>
              <p className="text-2xl font-bold text-yellow-600 font-mono">
                {formatDecimal(data.summary.pendingUsdt, 8)}
              </p>
            </div>
            <div className="text-center p-4 bg-muted rounded-lg">
              <p className="text-sm text-muted-foreground">可结算收益</p>
              <p className="text-2xl font-bold text-blue-600 font-mono">
                {formatDecimal(data.summary.settleableUsdt, 8)}
              </p>
            </div>
            <div className="text-center p-4 bg-muted rounded-lg">
              <p className="text-sm text-muted-foreground">已结算收益</p>
              <p className="text-2xl font-bold text-primary font-mono">
                {formatDecimal(data.summary.settledTotalUsdt, 8)}
              </p>
            </div>
            <div className="text-center p-4 bg-muted rounded-lg">
              <p className="text-sm text-muted-foreground">过期收益</p>
              <p className="text-2xl font-bold text-muted-foreground font-mono">
                {formatDecimal(data.summary.expiredTotalUsdt, 8)}
              </p>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 钱包分类账明细 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">钱包分类账明细</CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>流水ID</TableHead>
                  <TableHead>类型</TableHead>
                  <TableHead>资产</TableHead>
                  <TableHead className="text-right">金额</TableHead>
                  <TableHead className="text-right">余额快照</TableHead>
                  <TableHead>关联订单</TableHead>
                  <TableHead>备注</TableHead>
                  <TableHead>时间</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {data.items.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={8} className="text-center py-8 text-muted-foreground">
                      暂无钱包流水
                    </TableCell>
                  </TableRow>
                ) : (
                  data.items.map((item) => {
                    const amount = parseFloat(item.amount);
                    const isPositive = amount >= 0;
                    return (
                      <TableRow key={item.entryId}>
                        <TableCell className="font-mono text-xs">{item.entryId}</TableCell>
                        <TableCell className="text-sm">
                          {entryTypeLabels[item.entryType] || item.entryType}
                        </TableCell>
                        <TableCell className="text-sm">
                          {assetTypeLabels[item.assetType] || item.assetType}
                        </TableCell>
                        <TableCell className="text-right">
                          <span
                            className={cn(
                              'font-mono flex items-center justify-end gap-1',
                              isPositive ? 'text-green-600' : 'text-red-600'
                            )}
                          >
                            {isPositive ? (
                              <TrendingUp className="h-3 w-3" />
                            ) : (
                              <TrendingDown className="h-3 w-3" />
                            )}
                            {isPositive ? '+' : ''}
                            {formatDecimal(item.amount, 8)}
                          </span>
                        </TableCell>
                        <TableCell className="text-right font-mono text-sm">
                          {formatDecimal(item.balanceAfter, 8)}
                        </TableCell>
                        <TableCell className="font-mono text-xs text-muted-foreground max-w-[120px] truncate">
                          {item.refOrderId || item.refTxHash || '-'}
                        </TableCell>
                        <TableCell className="text-sm max-w-[100px] truncate" title={item.memo}>
                          {item.memo || '-'}
                        </TableCell>
                        <TableCell className="text-sm text-muted-foreground">
                          {formatDateTime(item.createdAt)}
                        </TableCell>
                      </TableRow>
                    );
                  })
                )}
              </TableBody>
            </Table>
          </div>

          {data.totalPages > 1 && (
            <div className="flex items-center justify-between p-4 border-t">
              <p className="text-sm text-muted-foreground">
                共 {formatNumber(data.total)} 条，第 {page} / {data.totalPages} 页
              </p>
              <div className="flex items-center gap-2">
                <Button variant="outline" size="sm" onClick={() => setPage(page - 1)} disabled={page <= 1}>
                  <ChevronLeft className="h-4 w-4" />
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setPage(page + 1)}
                  disabled={page >= data.totalPages}
                >
                  <ChevronRight className="h-4 w-4" />
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
