'use client';

import { useState } from 'react';
import { useParams } from 'next/navigation';
import Link from 'next/link';
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 {
  AlertCircle,
  RefreshCw,
  Pickaxe,
  Receipt,
  ChevronLeft,
  ChevronRight,
  FileStack,
} from 'lucide-react';
import { useQueryClient } from '@tanstack/react-query';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';

import {
  useSystemAccounts,
  useSystemAccountMiningRecords,
  useSystemAccountTransactions,
  useSystemAccountContributionRecords,
  useSystemAccountContributionStats,
} from '@/features/system-accounts';
import { ContributionRecordsTable } from '@/features/system-accounts/components';
import { getAccountDisplayInfo } from '@/types/system-account';
import { getRegionDisplayName } from '@/lib/constants/region-codes';
import { formatDecimal } from '@/lib/utils/format';

const TRANSACTION_TYPE_LABELS: Record<string, { label: string; color: string }> = {
  MINE: { label: '挖矿收益', color: 'bg-green-100 text-green-800' },
  TRANSFER_OUT: { label: '转出', color: 'bg-red-100 text-red-800' },
  TRANSFER_IN: { label: '转入', color: 'bg-blue-100 text-blue-800' },
  ADJUSTMENT: { label: '调整', color: 'bg-yellow-100 text-yellow-800' },
};

export default function SystemAccountDetailPage() {
  const params = useParams();
  const queryClient = useQueryClient();
  const accountType = params.accountType as string;

  const [miningPage, setMiningPage] = useState(1);
  const [transactionPage, setTransactionPage] = useState(1);
  const [transactionFilter, setTransactionFilter] = useState<string | null>(null);
  const [contributionPage, setContributionPage] = useState(1);
  const pageSize = 20;

  // 获取账户列表以找到当前账户信息
  const { data: accountsData, isLoading: accountsLoading } = useSystemAccounts();
  const currentAccount = accountsData?.accounts.find(
    (a) => a.accountType === accountType
  );

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

  // 获取交易记录
  const {
    data: transactions,
    isLoading: transactionsLoading,
    error: transactionsError,
  } = useSystemAccountTransactions(accountType, transactionPage, pageSize, transactionFilter);

  // 获取当前账户的 regionCode
  const regionCode = currentAccount?.regionCode ?? null;

  // 获取算力来源明细
  const {
    data: contributionRecords,
    isLoading: contributionLoading,
    error: contributionError,
  } = useSystemAccountContributionRecords(accountType, regionCode, contributionPage, pageSize);

  // 获取算力明细统计
  const { data: contributionStats } = useSystemAccountContributionStats(accountType, regionCode);

  const displayInfo = getAccountDisplayInfo(accountType);

  const handleRefresh = () => {
    queryClient.invalidateQueries({
      queryKey: ['system-accounts', accountType],
    });
  };

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

  // 使用前端区域代码映射获取显示名称
  const accountTitle = currentAccount?.regionCode
    ? getRegionDisplayName(currentAccount.regionCode, currentAccount.accountType)
    : (currentAccount?.name || displayInfo.label);

  return (
    <div className="space-y-6">
      {/* 自定义头部 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Link href="/system-accounts">
            <Button variant="ghost" size="icon" className="h-8 w-8">
              <ChevronLeft className="h-4 w-4" />
            </Button>
          </Link>
          <div className="flex items-center gap-3">
            <span
              className={`inline-block w-3 h-3 rounded-full ${displayInfo.color.replace('text-', 'bg-')}`}
            />
            <h1 className="text-2xl font-bold tracking-tight">{accountTitle}</h1>
            <code className="text-sm bg-muted px-2 py-1 rounded font-normal">
              {accountType}
            </code>
          </div>
        </div>
        <Button
          variant="outline"
          size="sm"
          onClick={handleRefresh}
          disabled={miningLoading || transactionsLoading}
        >
          <RefreshCw
            className={`h-4 w-4 mr-2 ${miningLoading || transactionsLoading ? 'animate-spin' : ''}`}
          />
          刷新
        </Button>
      </div>

      {/* 账户概览卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              当前算力
            </CardTitle>
          </CardHeader>
          <CardContent>
            {accountsLoading ? (
              <Skeleton className="h-8 w-32" />
            ) : (
              <div className="text-2xl font-bold">
                {formatDecimal(
                  currentAccount?.contributionBalance ||
                    currentAccount?.totalContribution ||
                    '0',
                  2
                )}
              </div>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              已挖积分股
            </CardTitle>
          </CardHeader>
          <CardContent>
            {accountsLoading ? (
              <Skeleton className="h-8 w-32" />
            ) : (
              <div className="text-2xl font-bold text-green-600">
                {formatDecimal(currentAccount?.totalMined || '0', 8)}
              </div>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              可用余额
            </CardTitle>
          </CardHeader>
          <CardContent>
            {accountsLoading ? (
              <Skeleton className="h-8 w-32" />
            ) : (
              <div className="text-2xl font-bold">
                {formatDecimal(currentAccount?.availableBalance || '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>

      {/* 分类账 Tabs */}
      <Tabs defaultValue="mining" className="space-y-4">
        <TabsList>
          <TabsTrigger value="mining" className="flex items-center gap-2">
            <Pickaxe className="h-4 w-4" />
            挖矿记录
          </TabsTrigger>
          <TabsTrigger value="transactions" className="flex items-center gap-2">
            <Receipt className="h-4 w-4" />
            交易记录
          </TabsTrigger>
          <TabsTrigger value="contributions" className="flex items-center gap-2">
            <FileStack className="h-4 w-4" />
            算力来源
          </TabsTrigger>
        </TabsList>

        {/* 挖矿记录 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 className="text-right">算力占比</TableHead>
                        <TableHead className="text-right">全网算力</TableHead>
                        <TableHead className="text-right">每秒分配量</TableHead>
                        <TableHead className="text-right">挖得数量</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {miningLoading ? (
                        [...Array(5)].map((_, i) => (
                          <TableRow key={i}>
                            {[...Array(5)].map((_, j) => (
                              <TableCell key={j}>
                                <Skeleton className="h-4 w-full" />
                              </TableCell>
                            ))}
                          </TableRow>
                        ))
                      ) : !miningRecords?.records.length ? (
                        <TableRow>
                          <TableCell
                            colSpan={5}
                            className="text-center text-muted-foreground py-8"
                          >
                            暂无挖矿记录
                          </TableCell>
                        </TableRow>
                      ) : (
                        miningRecords.records.map((record) => (
                          <TableRow key={record.id}>
                            <TableCell>
                              {format(
                                new Date(record.miningMinute),
                                'yyyy-MM-dd HH:mm',
                                { locale: zhCN }
                              )}
                            </TableCell>
                            <TableCell className="text-right font-mono">
                              {(Number(record.contributionRatio) * 100).toFixed(6)}%
                            </TableCell>
                            <TableCell className="text-right font-mono">
                              {formatDecimal(record.totalContribution, 2)}
                            </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>
                          </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>

        {/* 交易记录 Tab */}
        <TabsContent value="transactions">
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle className="text-lg flex items-center gap-2">
                  交易记录
                  {transactions && (
                    <Badge variant="secondary" className="text-xs">
                      共 {transactions.total} 条
                    </Badge>
                  )}
                </CardTitle>
                <div className="flex items-center gap-2">
                  <Button
                    variant={transactionFilter === null ? 'default' : 'outline'}
                    size="sm"
                    onClick={() => { setTransactionFilter(null); setTransactionPage(1); }}
                  >
                    全部
                  </Button>
                  <Button
                    variant={transactionFilter === 'BATCH_MINING' ? 'default' : 'outline'}
                    size="sm"
                    onClick={() => { setTransactionFilter('BATCH_MINING'); setTransactionPage(1); }}
                  >
                    批量补发
                  </Button>
                </div>
              </div>
            </CardHeader>
            <CardContent className="p-0">
              {transactionsError ? (
                <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>备注</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {transactionsLoading ? (
                        [...Array(5)].map((_, i) => (
                          <TableRow key={i}>
                            {[...Array(6)].map((_, j) => (
                              <TableCell key={j}>
                                <Skeleton className="h-4 w-full" />
                              </TableCell>
                            ))}
                          </TableRow>
                        ))
                      ) : !transactions?.transactions.length ? (
                        <TableRow>
                          <TableCell
                            colSpan={6}
                            className="text-center text-muted-foreground py-8"
                          >
                            暂无交易记录
                          </TableCell>
                        </TableRow>
                      ) : (
                        transactions.transactions.map((tx) => {
                          const typeInfo = TRANSACTION_TYPE_LABELS[tx.type] || {
                            label: tx.type,
                            color: 'bg-gray-100 text-gray-800',
                          };
                          const isPositive = Number(tx.amount) > 0;

                          return (
                            <TableRow key={tx.id}>
                              <TableCell>
                                {format(
                                  new Date(tx.createdAt),
                                  'yyyy-MM-dd HH:mm:ss',
                                  { locale: zhCN }
                                )}
                              </TableCell>
                              <TableCell>
                                <div className="flex items-center gap-1.5">
                                  <Badge className={`${typeInfo.color} text-xs`}>
                                    {typeInfo.label}
                                  </Badge>
                                  {tx.referenceType === 'BATCH_MINING' && (
                                    <Badge variant="outline" className="text-xs bg-violet-50 text-violet-700 border-violet-200">
                                      批量补发
                                    </Badge>
                                  )}
                                </div>
                              </TableCell>
                              <TableCell
                                className={`text-right font-mono ${
                                  isPositive ? 'text-green-600' : 'text-red-600'
                                }`}
                              >
                                {isPositive ? '+' : ''}
                                {formatDecimal(tx.amount, 8)}
                              </TableCell>
                              <TableCell className="text-right font-mono">
                                {formatDecimal(tx.balanceBefore, 8)}
                              </TableCell>
                              <TableCell className="text-right font-mono">
                                {formatDecimal(tx.balanceAfter, 8)}
                              </TableCell>
                              <TableCell className="text-muted-foreground text-sm max-w-[200px] truncate">
                                {tx.memo || '-'}
                              </TableCell>
                            </TableRow>
                          );
                        })
                      )}
                    </TableBody>
                  </Table>

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

        {/* 算力来源 Tab */}
        <TabsContent value="contributions">
          {contributionError ? (
            <Alert variant="destructive">
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>加载算力来源记录失败</AlertDescription>
            </Alert>
          ) : (
            <ContributionRecordsTable
              records={contributionRecords?.records || []}
              stats={contributionStats}
              isLoading={contributionLoading}
              page={contributionPage}
              pageSize={pageSize}
              total={contributionRecords?.total || 0}
              totalPages={contributionRecords ? Math.ceil(contributionRecords.total / pageSize) : 0}
              onPageChange={setContributionPage}
            />
          )}
        </TabsContent>
      </Tabs>
    </div>
  );
}
