'use client';

import { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  AlertCircle,
  RefreshCw,
  Pickaxe,
  List,
  ChevronLeft,
  ChevronRight,
} from 'lucide-react';
import { useQueryClient } from '@tanstack/react-query';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';

import {
  usePendingContributions,
  usePendingContributionsSummary,
  useAllPendingMiningRecords,
} from '@/features/pending-contributions';
import { formatDecimal } from '@/lib/utils/format';
import { PageHeader } from '@/components/layout/page-header';

const CONTRIBUTION_TYPE_LABELS: Record<string, { label: string; color: string }> = {
  LEVEL_1: { label: '一级', color: 'bg-blue-100 text-blue-800' },
  LEVEL_2: { label: '二级', color: 'bg-green-100 text-green-800' },
  LEVEL_3: { label: '三级', color: 'bg-purple-100 text-purple-800' },
  BONUS_1: { label: '奖励一级', color: 'bg-orange-100 text-orange-800' },
  BONUS_2: { label: '奖励二级', color: 'bg-yellow-100 text-yellow-800' },
  BONUS_3: { label: '奖励三级', color: 'bg-red-100 text-red-800' },
};

export default function PendingContributionsPage() {
  const queryClient = useQueryClient();

  const [listPage, setListPage] = useState(1);
  const [miningPage, setMiningPage] = useState(1);
  const [typeFilter, setTypeFilter] = useState<string>('all');
  const pageSize = 20;

  // 获取汇总统计
  const {
    data: summary,
    isLoading: summaryLoading,
    error: summaryError,
  } = usePendingContributionsSummary();

  // 获取待解锁算力列表
  const {
    data: contributions,
    isLoading: listLoading,
    error: listError,
  } = usePendingContributions(
    listPage,
    pageSize,
    typeFilter !== 'all' ? typeFilter : undefined
  );

  // 获取所有挖矿记录
  const {
    data: miningRecords,
    isLoading: miningLoading,
    error: miningError,
  } = useAllPendingMiningRecords(miningPage, pageSize);

  const handleRefresh = () => {
    queryClient.invalidateQueries({ queryKey: ['pending-contributions'] });
  };

  const listTotalPages = contributions
    ? Math.ceil(contributions.total / pageSize)
    : 0;
  const miningTotalPages = miningRecords
    ? Math.ceil(miningRecords.total / pageSize)
    : 0;

  return (
    <div className="space-y-6">
      <PageHeader
        title="待解锁算力分类账"
        description="查看未满足解锁条件的算力及其挖矿收益（归入总部账户）"
        actions={
          <Button
            variant="outline"
            size="sm"
            onClick={handleRefresh}
            disabled={listLoading || miningLoading}
          >
            <RefreshCw
              className={`h-4 w-4 mr-2 ${listLoading || miningLoading ? 'animate-spin' : ''}`}
            />
            刷新
          </Button>
        }
      />

      {/* 汇总统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              待解锁算力总量
            </CardTitle>
          </CardHeader>
          <CardContent>
            {summaryLoading ? (
              <Skeleton className="h-8 w-32" />
            ) : summaryError ? (
              <span className="text-red-500 text-sm">加载失败</span>
            ) : (
              <>
                <div className="text-2xl font-bold text-yellow-600">
                  {formatDecimal(summary?.total?.totalAmount || '0', 2)}
                </div>
                <div className="text-xs text-muted-foreground mt-1">
                  共 {summary?.total?.count || 0} 条记录
                </div>
              </>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              已归入总部积分股
            </CardTitle>
          </CardHeader>
          <CardContent>
            {summaryLoading ? (
              <Skeleton className="h-8 w-32" />
            ) : summaryError ? (
              <span className="text-red-500 text-sm">加载失败</span>
            ) : (
              <div className="text-2xl font-bold text-green-600">
                {formatDecimal(summary?.totalMinedToHeadquarters || '0', 8)}
              </div>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              挖矿记录数
            </CardTitle>
          </CardHeader>
          <CardContent>
            {miningLoading ? (
              <Skeleton className="h-8 w-20" />
            ) : (
              <div className="text-2xl font-bold">{miningRecords?.total || 0}</div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* 按类型统计 */}
      {summary?.byType && summary.byType.length > 0 && (
        <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">
              {summary.byType.map((item) => {
                const typeInfo = CONTRIBUTION_TYPE_LABELS[item.contributionType] || {
                  label: item.contributionType,
                  color: 'bg-gray-100 text-gray-800',
                };
                return (
                  <div
                    key={item.contributionType}
                    className="p-3 rounded-lg border bg-card"
                  >
                    <Badge className={`${typeInfo.color} mb-2`}>
                      {typeInfo.label}
                    </Badge>
                    <div className="space-y-1">
                      <div className="text-sm text-muted-foreground">
                        算力: <span className="font-mono text-yellow-600">{formatDecimal(item.totalAmount, 2)}</span>
                      </div>
                      <div className="text-sm text-muted-foreground">
                        记录数: <span className="font-mono">{item.count}</span>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </CardContent>
        </Card>
      )}

      {/* 分类账 Tabs */}
      <Tabs defaultValue="list" className="space-y-4">
        <TabsList>
          <TabsTrigger value="list" className="flex items-center gap-2">
            <List className="h-4 w-4" />
            算力列表
          </TabsTrigger>
          <TabsTrigger value="mining" className="flex items-center gap-2">
            <Pickaxe className="h-4 w-4" />
            挖矿记录
          </TabsTrigger>
        </TabsList>

        {/* 算力列表 Tab */}
        <TabsContent value="list">
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle className="text-lg flex items-center gap-2">
                  待解锁算力列表
                  {contributions && (
                    <Badge variant="secondary" className="text-xs">
                      共 {contributions.total} 条
                    </Badge>
                  )}
                </CardTitle>
                <Select value={typeFilter} onValueChange={setTypeFilter}>
                  <SelectTrigger className="w-[150px]">
                    <SelectValue placeholder="选择类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">全部类型</SelectItem>
                    {Object.entries(CONTRIBUTION_TYPE_LABELS).map(([key, info]) => (
                      <SelectItem key={key} value={key}>
                        {info.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </CardHeader>
            <CardContent className="p-0">
              {listError ? (
                <Alert variant="destructive" className="m-4">
                  <AlertCircle className="h-4 w-4" />
                  <AlertDescription>加载列表失败</AlertDescription>
                </Alert>
              ) : (
                <>
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>来源用户</TableHead>
                        <TableHead>归属用户</TableHead>
                        <TableHead>类型</TableHead>
                        <TableHead className="text-right">算力</TableHead>
                        <TableHead>原因</TableHead>
                        <TableHead>创建时间</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {listLoading ? (
                        [...Array(5)].map((_, i) => (
                          <TableRow key={i}>
                            {[...Array(6)].map((_, j) => (
                              <TableCell key={j}>
                                <Skeleton className="h-4 w-full" />
                              </TableCell>
                            ))}
                          </TableRow>
                        ))
                      ) : !contributions?.contributions.length ? (
                        <TableRow>
                          <TableCell
                            colSpan={6}
                            className="text-center text-muted-foreground py-8"
                          >
                            暂无数据
                          </TableCell>
                        </TableRow>
                      ) : (
                        contributions.contributions.map((item) => {
                          const typeInfo = CONTRIBUTION_TYPE_LABELS[item.contributionType] || {
                            label: item.contributionType,
                            color: 'bg-gray-100 text-gray-800',
                          };
                          return (
                            <TableRow key={item.id}>
                              <TableCell>
                                <code className="text-xs bg-muted px-1 py-0.5 rounded">
                                  {item.sourceAccountSequence}
                                </code>
                              </TableCell>
                              <TableCell>
                                <code className="text-xs bg-muted px-1 py-0.5 rounded">
                                  {item.wouldBeAccountSequence}
                                </code>
                              </TableCell>
                              <TableCell>
                                <Badge className={`${typeInfo.color} text-xs`}>
                                  {typeInfo.label}
                                </Badge>
                              </TableCell>
                              <TableCell className="text-right font-mono text-yellow-600">
                                {formatDecimal(item.amount, 2)}
                              </TableCell>
                              <TableCell className="text-muted-foreground text-sm max-w-[200px] truncate">
                                {item.reason || '-'}
                              </TableCell>
                              <TableCell>
                                {format(
                                  new Date(item.createdAt),
                                  'yyyy-MM-dd HH:mm',
                                  { locale: zhCN }
                                )}
                              </TableCell>
                            </TableRow>
                          );
                        })
                      )}
                    </TableBody>
                  </Table>

                  {/* 分页 */}
                  {listTotalPages > 1 && (
                    <div className="flex items-center justify-center gap-2 py-4">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setListPage((p) => Math.max(1, p - 1))}
                        disabled={listPage <= 1}
                      >
                        <ChevronLeft className="h-4 w-4" />
                        上一页
                      </Button>
                      <span className="text-sm text-muted-foreground px-4">
                        第 {listPage} / {listTotalPages} 页
                      </span>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() =>
                          setListPage((p) => Math.min(listTotalPages, p + 1))
                        }
                        disabled={listPage >= listTotalPages}
                      >
                        下一页
                        <ChevronRight className="h-4 w-4" />
                      </Button>
                    </div>
                  )}
                </>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* 挖矿记录 Tab */}
        <TabsContent value="mining">
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center gap-2">
                挖矿记录
                {miningRecords && (
                  <Badge variant="secondary" className="text-xs">
                    共 {miningRecords.total} 条
                  </Badge>
                )}
              </CardTitle>
            </CardHeader>
            <CardContent className="p-0">
              {miningError ? (
                <Alert variant="destructive" className="m-4">
                  <AlertCircle className="h-4 w-4" />
                  <AlertDescription>加载挖矿记录失败</AlertDescription>
                </Alert>
              ) : (
                <>
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>挖矿时间</TableHead>
                        <TableHead>类型</TableHead>
                        <TableHead className="text-right">算力</TableHead>
                        <TableHead className="text-right">算力占比</TableHead>
                        <TableHead className="text-right">每秒分配量</TableHead>
                        <TableHead className="text-right">挖得数量</TableHead>
                        <TableHead>归入</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {miningLoading ? (
                        [...Array(5)].map((_, i) => (
                          <TableRow key={i}>
                            {[...Array(7)].map((_, j) => (
                              <TableCell key={j}>
                                <Skeleton className="h-4 w-full" />
                              </TableCell>
                            ))}
                          </TableRow>
                        ))
                      ) : !miningRecords?.records.length ? (
                        <TableRow>
                          <TableCell
                            colSpan={7}
                            className="text-center text-muted-foreground py-8"
                          >
                            暂无挖矿记录
                          </TableCell>
                        </TableRow>
                      ) : (
                        miningRecords.records.map((record) => {
                          const typeInfo = CONTRIBUTION_TYPE_LABELS[record.contributionType || ''] || {
                            label: record.contributionType || '-',
                            color: 'bg-gray-100 text-gray-800',
                          };
                          return (
                            <TableRow key={record.id}>
                              <TableCell>
                                {format(
                                  new Date(record.miningMinute),
                                  'yyyy-MM-dd HH:mm',
                                  { locale: zhCN }
                                )}
                              </TableCell>
                              <TableCell>
                                <Badge className={`${typeInfo.color} text-xs`}>
                                  {typeInfo.label}
                                </Badge>
                              </TableCell>
                              <TableCell className="text-right font-mono">
                                {formatDecimal(record.contributionAmount, 2)}
                              </TableCell>
                              <TableCell className="text-right font-mono">
                                {(Number(record.contributionRatio) * 100).toFixed(6)}%
                              </TableCell>
                              <TableCell className="text-right font-mono">
                                {formatDecimal(record.secondDistribution, 8)}
                              </TableCell>
                              <TableCell className="text-right font-mono text-green-600">
                                +{formatDecimal(record.minedAmount, 8)}
                              </TableCell>
                              <TableCell>
                                <Badge variant="outline" className="text-xs">
                                  {record.allocatedTo === 'HEADQUARTERS' ? '总部' : record.allocatedTo}
                                </Badge>
                              </TableCell>
                            </TableRow>
                          );
                        })
                      )}
                    </TableBody>
                  </Table>

                  {/* 分页 */}
                  {miningTotalPages > 1 && (
                    <div className="flex items-center justify-center gap-2 py-4">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => setMiningPage((p) => Math.max(1, p - 1))}
                        disabled={miningPage <= 1}
                      >
                        <ChevronLeft className="h-4 w-4" />
                        上一页
                      </Button>
                      <span className="text-sm text-muted-foreground px-4">
                        第 {miningPage} / {miningTotalPages} 页
                      </span>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() =>
                          setMiningPage((p) => Math.min(miningTotalPages, p + 1))
                        }
                        disabled={miningPage >= miningTotalPages}
                      >
                        下一页
                        <ChevronRight className="h-4 w-4" />
                      </Button>
                    </div>
                  )}
                </>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
