'use client';

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Button } from '@/components/ui/button';
import { formatDecimal } from '@/lib/utils/format';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { ChevronLeft, ChevronRight, Users, FileStack, TrendingUp } from 'lucide-react';
import type { SystemContributionRecord, SystemContributionStats, ContributionSourceType } from '../api/system-accounts.api';

// 来源类型显示名称映射
const SOURCE_TYPE_LABELS: Record<ContributionSourceType, string> = {
  FIXED_RATE: '固定比例',
  LEVEL_OVERFLOW: '层级溢出',
  LEVEL_NO_ANCESTOR: '无上线',
  BONUS_TIER_1: '团队T1',
  BONUS_TIER_2: '团队T2',
  BONUS_TIER_3: '团队T3',
};

// 来源类型颜色映射
const SOURCE_TYPE_COLORS: Record<ContributionSourceType, string> = {
  FIXED_RATE: 'bg-green-100 text-green-800',
  LEVEL_OVERFLOW: 'bg-orange-100 text-orange-800',
  LEVEL_NO_ANCESTOR: 'bg-red-100 text-red-800',
  BONUS_TIER_1: 'bg-purple-100 text-purple-800',
  BONUS_TIER_2: 'bg-purple-100 text-purple-800',
  BONUS_TIER_3: 'bg-purple-100 text-purple-800',
};

// 获取来源类型显示文本
function getSourceTypeDisplay(sourceType: ContributionSourceType, levelDepth: number | null): string {
  if (sourceType === 'LEVEL_OVERFLOW' || sourceType === 'LEVEL_NO_ANCESTOR') {
    return `${SOURCE_TYPE_LABELS[sourceType]}(第${levelDepth}级)`;
  }
  return SOURCE_TYPE_LABELS[sourceType] || sourceType;
}

interface ContributionRecordsTableProps {
  records: SystemContributionRecord[];
  stats?: SystemContributionStats;
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
  isLoading?: boolean;
  onPageChange: (page: number) => void;
}

export function ContributionRecordsTable({
  records,
  stats,
  total,
  page,
  pageSize,
  totalPages,
  isLoading = false,
  onPageChange,
}: ContributionRecordsTableProps) {
  return (
    <div className="space-y-4">
      {/* 统计卡片 */}
      {stats && (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <Card>
            <CardHeader className="pb-2">
              <CardDescription className="flex items-center gap-2">
                <FileStack className="h-4 w-4" />
                算力明细记录数
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats.recordCount}</div>
              <p className="text-xs text-muted-foreground mt-1">
                合计: {formatDecimal(stats.sumFromRecords, 4)}
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-2">
              <CardDescription className="flex items-center gap-2">
                <TrendingUp className="h-4 w-4" />
                来源认种订单数
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats.uniqueAdoptionCount}</div>
              <p className="text-xs text-muted-foreground mt-1">
                去重后的认种订单
              </p>
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-2">
              <CardDescription className="flex items-center gap-2">
                <Users className="h-4 w-4" />
                来源用户数
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{stats.uniqueUserCount}</div>
              <p className="text-xs text-muted-foreground mt-1">
                去重后的认种用户
              </p>
            </CardContent>
          </Card>
        </div>
      )}

      {/* 表格 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg flex items-center gap-2">
            算力来源明细
            <Badge variant="secondary" className="text-xs">
              共 {total} 条记录
            </Badge>
          </CardTitle>
          <CardDescription>
            显示该账户的每笔算力来自哪个认种订单
          </CardDescription>
        </CardHeader>
        <CardContent className="p-0">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>认种订单</TableHead>
                <TableHead>认种用户</TableHead>
                <TableHead>来源类型</TableHead>
                <TableHead className="text-right">认种树数</TableHead>
                <TableHead className="text-right">分配比例</TableHead>
                <TableHead className="text-right">算力金额</TableHead>
                <TableHead>生效日期</TableHead>
                <TableHead>创建时间</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading ? (
                [...Array(5)].map((_, i) => (
                  <TableRow key={i}>
                    {[...Array(8)].map((_, j) => (
                      <TableCell key={j}>
                        <Skeleton className="h-4 w-full" />
                      </TableCell>
                    ))}
                  </TableRow>
                ))
              ) : records.length === 0 ? (
                <TableRow>
                  <TableCell
                    colSpan={8}
                    className="text-center text-muted-foreground py-8"
                  >
                    暂无算力来源记录
                  </TableCell>
                </TableRow>
              ) : (
                records.map((record) => (
                  <TableRow key={record.originalRecordId}>
                    <TableCell>
                      <div className="flex flex-col gap-0.5">
                        <code className="text-xs bg-muted px-1.5 py-0.5 rounded inline-block w-fit">
                          #{record.sourceAdoptionId}
                        </code>
                        {record.adoptionDate && (
                          <span className="text-xs text-muted-foreground">
                            {format(new Date(record.adoptionDate), 'yyyy-MM-dd', { locale: zhCN })}
                          </span>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="flex flex-col gap-0.5">
                        <code className="text-xs bg-blue-50 text-blue-700 px-1.5 py-0.5 rounded inline-block w-fit">
                          {record.sourceAccountSequence}
                        </code>
                        {(record.sourceUserName || record.sourceUserPhone) && (
                          <span className="text-xs text-muted-foreground">
                            {record.sourceUserName || record.sourceUserPhone}
                          </span>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge
                        variant="secondary"
                        className={`text-xs ${SOURCE_TYPE_COLORS[record.sourceType] || 'bg-gray-100 text-gray-800'}`}
                      >
                        {getSourceTypeDisplay(record.sourceType, record.levelDepth)}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-right">
                      <span className="font-mono text-sm">
                        {record.adoptionTreeCount > 0 ? record.adoptionTreeCount : '-'}
                      </span>
                    </TableCell>
                    <TableCell className="text-right">
                      <Badge variant="outline" className="font-mono">
                        {(Number(record.distributionRate) * 100).toFixed(2)}%
                      </Badge>
                    </TableCell>
                    <TableCell className="text-right font-mono text-green-600">
                      +{formatDecimal(record.amount, 4)}
                    </TableCell>
                    <TableCell className="text-muted-foreground text-sm">
                      {format(new Date(record.effectiveDate), 'yyyy-MM-dd', { locale: zhCN })}
                    </TableCell>
                    <TableCell className="text-muted-foreground text-sm">
                      {format(new Date(record.createdAt), 'yyyy-MM-dd HH:mm', { locale: zhCN })}
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>

          {/* 分页 */}
          {totalPages > 1 && (
            <div className="flex items-center justify-between px-4 py-3 border-t">
              <div className="text-sm text-muted-foreground">
                第 {page} / {totalPages} 页，共 {total} 条
              </div>
              <div className="flex items-center gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => onPageChange(page - 1)}
                  disabled={page <= 1}
                >
                  <ChevronLeft className="h-4 w-4" />
                  上一页
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => onPageChange(page + 1)}
                  disabled={page >= totalPages}
                >
                  下一页
                  <ChevronRight className="h-4 w-4" />
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
