'use client';

import { useState } from 'react';
import { useContributionRecords } from '../hooks/use-users';
import { formatDecimal, formatPercent } from '@/lib/utils/format';
import { formatDateTime, formatDate } from '@/lib/utils/date';
import { Card, CardContent } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { Badge } from '@/components/ui/badge';
import { ChevronLeft, ChevronRight, ArrowUpDown, ArrowUp, ArrowDown } from 'lucide-react';

type SortField = 'sourceType' | 'levelDepth' | 'amount' | 'createdAt';
type SortOrder = 'asc' | 'desc';

const sourceTypeLabels: Record<string, string> = {
  PERSONAL: '个人认种',
  TEAM_LEVEL: '团队层级',
  TEAM_BONUS: '团队奖励',
};

const sourceTypeBadgeVariant: Record<string, 'default' | 'secondary' | 'outline'> = {
  PERSONAL: 'default',
  TEAM_LEVEL: 'secondary',
  TEAM_BONUS: 'outline',
};

function SortableHeader({
  label,
  field,
  currentSort,
  currentOrder,
  onSort,
  className,
}: {
  label: string;
  field: SortField;
  currentSort?: SortField;
  currentOrder: SortOrder;
  onSort: (field: SortField) => void;
  className?: string;
}) {
  const isActive = currentSort === field;
  return (
    <TableHead className={className}>
      <button
        className="flex items-center gap-1 hover:text-foreground transition-colors -ml-1 px-1 py-0.5 rounded"
        onClick={() => onSort(field)}
      >
        {label}
        {isActive ? (
          currentOrder === 'asc' ? (
            <ArrowUp className="h-3.5 w-3.5 text-primary" />
          ) : (
            <ArrowDown className="h-3.5 w-3.5 text-primary" />
          )
        ) : (
          <ArrowUpDown className="h-3.5 w-3.5 opacity-40" />
        )}
      </button>
    </TableHead>
  );
}

interface ContributionRecordsListProps {
  accountSequence: string;
}

export function ContributionRecordsList({ accountSequence }: ContributionRecordsListProps) {
  const [page, setPage] = useState(1);
  const pageSize = 10;
  const [sortBy, setSortBy] = useState<SortField | undefined>(undefined);
  const [sortOrder, setSortOrder] = useState<SortOrder>('asc');

  const handleSort = (field: SortField) => {
    if (sortBy === field) {
      // 同一字段：切换方向 → 第三次点击取消排序
      if (sortOrder === 'asc') {
        setSortOrder('desc');
      } else {
        setSortBy(undefined);
        setSortOrder('asc');
      }
    } else {
      setSortBy(field);
      setSortOrder('asc');
    }
    setPage(1);
  };

  const { data, isLoading } = useContributionRecords(accountSequence, {
    page,
    pageSize,
    sortBy,
    sortOrder: sortBy ? sortOrder : undefined,
  });

  return (
    <Card>
      <CardContent className="p-0">
        <Table>
          <TableHeader>
            <TableRow>
              <SortableHeader label="来源" field="sourceType" currentSort={sortBy} currentOrder={sortOrder} onSort={handleSort} />
              <TableHead>来源用户</TableHead>
              <TableHead className="text-right">棵数</TableHead>
              <TableHead className="text-right">基础算力</TableHead>
              <TableHead className="text-right">分配比例</TableHead>
              <SortableHeader label="获得算力" field="amount" currentSort={sortBy} currentOrder={sortOrder} onSort={handleSort} className="text-right" />
              <SortableHeader label="层级/等级" field="levelDepth" currentSort={sortBy} currentOrder={sortOrder} onSort={handleSort} />
              <SortableHeader label="生效日期" field="createdAt" currentSort={sortBy} currentOrder={sortOrder} onSort={handleSort} />
              <TableHead>状态</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {isLoading ? (
              [...Array(5)].map((_, i) => (
                <TableRow key={i}>
                  {[...Array(9)].map((_, j) => (
                    <TableCell key={j}>
                      <Skeleton className="h-4 w-full" />
                    </TableCell>
                  ))}
                </TableRow>
              ))
            ) : data?.items.length === 0 ? (
              <TableRow>
                <TableCell colSpan={9} className="text-center py-8 text-muted-foreground">
                  暂无算力记录
                </TableCell>
              </TableRow>
            ) : (
              data?.items.map((record) => (
                <TableRow key={record.id} className={record.isExpired ? 'opacity-50' : ''}>
                  <TableCell>
                    <Badge variant={sourceTypeBadgeVariant[record.sourceType] || 'default'}>
                      {sourceTypeLabels[record.sourceType] || record.sourceType}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    {record.sourceType === 'PERSONAL' ? (
                      <span className="text-muted-foreground">本人</span>
                    ) : record.sourceUserInfo ? (
                      <div className="flex flex-col">
                        <span className="font-medium">{record.sourceUserInfo.nickname || record.sourceUserInfo.phone}</span>
                        <span className="text-xs text-muted-foreground font-mono">{record.sourceAccountSequence}</span>
                      </div>
                    ) : (
                      <span className="font-mono text-sm">{record.sourceAccountSequence}</span>
                    )}
                  </TableCell>
                  <TableCell className="text-right">{record.treeCount}</TableCell>
                  <TableCell className="text-right font-mono">{formatDecimal(record.baseContribution, 8)}</TableCell>
                  <TableCell className="text-right">{formatPercent(record.distributionRate)}</TableCell>
                  <TableCell className="text-right font-mono font-medium">{formatDecimal(record.amount, 8)}</TableCell>
                  <TableCell>
                    {record.levelDepth !== null
                      ? `L${record.levelDepth}`
                      : record.bonusTier !== null
                        ? `T${record.bonusTier}`
                        : '-'}
                  </TableCell>
                  <TableCell className="text-sm">{formatDate(record.effectiveDate)}</TableCell>
                  <TableCell>
                    {record.isExpired ? (
                      <Badge variant="destructive">无效</Badge>
                    ) : (
                      <Badge className="border-transparent bg-green-500 text-white hover:bg-green-500/80">有效</Badge>
                    )}
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>

        {data && data.totalPages > 1 && (
          <div className="flex items-center justify-between p-4 border-t">
            <p className="text-sm text-muted-foreground">
              共 {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>
  );
}
