'use client';

import { useParams } from 'next/navigation';
import Link from 'next/link';
import { PageHeader } from '@/components/layout/page-header';
import { useUserDetail, usePrePlantingRestriction, useUnlockPrePlantingRestriction } from '@/features/users/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 { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Skeleton } from '@/components/ui/skeleton';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { ContributionRecordsList } from '@/features/users/components/contribution-records-list';
import { MiningRecordsList } from '@/features/users/components/mining-records-list';
import { TradeOrdersList } from '@/features/users/components/trade-orders-list';
import { ReferralTree } from '@/features/users/components/referral-tree';
import { PlantingLedger } from '@/features/users/components/planting-ledger';
import { WalletLedger } from '@/features/users/components/wallet-ledger';
import { BatchMiningRecordsList } from '@/features/users/components/batch-mining-records-list';
import { CapabilityManagement } from '@/features/users/components/capability-management';
import { Users, TreePine, Wallet, Zap, ShoppingCart, Network, Coins, Gift, Shield, Lock, Unlock } from 'lucide-react';

function UserDetailSkeleton() {
  return (
    <div className="space-y-6">
      <Card>
        <CardContent className="p-6">
          <div className="grid grid-cols-4 gap-6">
            {[...Array(8)].map((_, i) => (
              <div key={i}>
                <Skeleton className="h-4 w-20 mb-2" />
                <Skeleton className="h-6 w-32" />
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

export default function UserDetailPage() {
  const params = useParams();
  const accountSequence = params.accountSequence as string;
  const { data: user, isLoading } = useUserDetail(accountSequence);
  const { data: restrictionData } = usePrePlantingRestriction(accountSequence);
  const unlockMutation = useUnlockPrePlantingRestriction(accountSequence);

  const handleUnlockRestriction = async () => {
    if (!confirm(`确认解除用户 ${accountSequence} 的预种卖出限制？\n解除后该用户可立即卖出积分股，此操作将记录审计日志。`)) return;
    try {
      await unlockMutation.mutateAsync('管理员手动解除');
      alert('已成功解除预种卖出限制');
    } catch {
      alert('解除失败，请重试');
    }
  };

  if (isLoading) {
    return (
      <div className="space-y-6">
        <PageHeader title="用户详情" backLink="/users" />
        <UserDetailSkeleton />
      </div>
    );
  }

  // 获取状态徽章
  const getStatusBadge = () => {
    if (user?.status === 'frozen') {
      return <Badge variant="destructive">冻结</Badge>;
    }
    if (user?.status === 'deactivated') {
      return <Badge variant="secondary">停用</Badge>;
    }
    if (user?.isOnline) {
      return <Badge className="bg-green-500">在线</Badge>;
    }
    return <Badge variant="outline">正常</Badge>;
  };

  return (
    <div className="space-y-6">
      <PageHeader title="用户详情" description={`账户序列: ${accountSequence}`} backLink="/users" />

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 基本信息卡片 */}
        <Card className="lg:col-span-2">
          <CardHeader>
            <CardTitle className="text-lg">基本信息</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex items-start gap-6 mb-6">
              <div className="relative">
                <Avatar className="h-20 w-20">
                  <AvatarImage src={user?.avatar || undefined} alt={user?.nickname || ''} />
                  <AvatarFallback className="text-2xl">{user?.nickname?.charAt(0) || 'U'}</AvatarFallback>
                </Avatar>
                {user?.isOnline && (
                  <span className="absolute bottom-1 right-1 w-4 h-4 bg-green-500 rounded-full border-2 border-white" />
                )}
              </div>
              <div className="flex-1">
                <div className="flex items-center gap-3 mb-2">
                  <h2 className="text-xl font-semibold">{user?.nickname || '未设置昵称'}</h2>
                  {getStatusBadge()}
                </div>
                <div className="grid grid-cols-2 md:grid-cols-3 gap-4 text-sm">
                  <div>
                    <span className="text-muted-foreground">账户序列:</span>
                    <span className="ml-2 font-mono font-medium">{user?.accountSequence}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">手机号:</span>
                    <span className="ml-2">{user?.phoneNumberMasked || user?.phone}</span>
                  </div>
                  <div>
                    <span className="text-muted-foreground">KYC状态:</span>
                    <span className="ml-2">{user?.kycStatus || '未认证'}</span>
                  </div>
                </div>
              </div>
            </div>

            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="p-3 bg-muted rounded-lg">
                <p className="text-sm text-muted-foreground flex items-center gap-1">
                  <Users className="h-3 w-3" /> 推荐人
                </p>
                {user?.referrerAccountSequence ? (
                  <Link
                    href={`/users/${user.referrerAccountSequence}`}
                    className="font-mono font-medium text-primary hover:underline"
                  >
                    {user.referrerAccountSequence}
                  </Link>
                ) : (
                  <p className="font-medium">-</p>
                )}
              </div>
              <div className="p-3 bg-muted rounded-lg">
                <p className="text-sm text-muted-foreground">直推人数</p>
                <p className="font-medium">{formatNumber(user?.directReferralCount)}</p>
              </div>
              <div className="p-3 bg-muted rounded-lg">
                <p className="text-sm text-muted-foreground">直推认种</p>
                <p className="font-medium">{formatNumber(user?.directReferralAdoptedCount)}</p>
              </div>
              <div className="p-3 bg-muted rounded-lg">
                <p className="text-sm text-muted-foreground">注册时间</p>
                <p className="text-sm">{formatDateTime(user?.registeredAt || user?.createdAt)}</p>
              </div>
            </div>

            {/* 认种统计 */}
            <div className="mt-4 grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="p-3 bg-green-50 dark:bg-green-950 rounded-lg">
                <p className="text-sm text-muted-foreground flex items-center gap-1">
                  <TreePine className="h-3 w-3 text-green-600" /> 个人认种
                </p>
                <p className="text-lg font-bold text-green-600">
                  {formatNumber(user?.personalAdoptions ?? 0)}
                  {(user?.personalAdoptionOrders ?? 0) > 0 && (
                    <span className="text-sm font-normal text-green-500 ml-1">
                      ({user?.personalAdoptionOrders}单)
                    </span>
                  )}
                </p>
              </div>
              <div className="p-3 bg-blue-50 dark:bg-blue-950 rounded-lg">
                <p className="text-sm text-muted-foreground flex items-center gap-1">
                  <Users className="h-3 w-3 text-blue-600" /> 团队认种
                </p>
                <p className="text-lg font-bold text-blue-600">
                  {formatNumber(user?.teamAdoptions ?? 0)}
                  {(user?.teamAdoptionOrders ?? 0) > 0 && (
                    <span className="text-sm font-normal text-blue-500 ml-1">
                      ({user?.teamAdoptionOrders}单)
                    </span>
                  )}
                </p>
              </div>
              <div className="p-3 bg-purple-50 dark:bg-purple-950 rounded-lg">
                <p className="text-sm text-muted-foreground">团队地址</p>
                <p className="text-lg font-bold text-purple-600">{formatNumber(user?.teamAddresses ?? 0)}</p>
              </div>
              <div className="p-3 bg-amber-50 dark:bg-amber-950 rounded-lg">
                <p className="text-sm text-muted-foreground">龙虎榜排名</p>
                <p className="text-lg font-bold text-amber-600">
                  {user?.ranking ? `#${user.ranking}` : '-'}
                </p>
              </div>
            </div>
            {/* 预种卖出限制（仅受限时显示） */}
            {restrictionData?.isRestricted && (
              <div className="mt-4 p-3 bg-red-50 dark:bg-red-950 rounded-lg border border-red-200 dark:border-red-800">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <Lock className="h-4 w-4 text-red-600" />
                    <div>
                      <p className="text-sm font-medium text-red-700 dark:text-red-300">预种卖出限制中</p>
                      <p className="text-xs text-red-600 dark:text-red-400">该用户仅有预种份数，尚未合并成棵，无法卖出积分股</p>
                    </div>
                  </div>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={handleUnlockRestriction}
                    disabled={unlockMutation.isPending}
                    className="border-red-300 text-red-700 hover:bg-red-100 dark:border-red-700 dark:text-red-300"
                  >
                    <Unlock className="h-3 w-3 mr-1" />
                    {unlockMutation.isPending ? '解除中...' : '手动解除限制'}
                  </Button>
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* 算力构成卡片 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg flex items-center gap-2">
              <Zap className="h-5 w-5 text-primary" />
              算力构成
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* 个人算力 */}
            <div className="flex justify-between items-center">
              <span className="text-sm text-muted-foreground">个人算力 (70%)</span>
              <span className="font-mono font-medium">{formatDecimal(user?.contributions?.personal, 8)}</span>
            </div>

            {/* 层级算力 */}
            <div className="space-y-2">
              <div className="flex justify-between items-center">
                <span className="text-sm text-muted-foreground">层级算力 (7.5%)</span>
                <span className="font-mono font-medium">{formatDecimal(user?.contributions?.teamLevel, 8)}</span>
              </div>
              <div className="pl-3 space-y-1 text-xs">
                <div className="flex items-center gap-2">
                  {(user?.contributions?.unlockedLevelDepth ?? 0) >= 5 ? (
                    <span className="text-green-600">✓</span>
                  ) : (
                    <span className="text-muted-foreground">✗</span>
                  )}
                  <span className={`${(user?.contributions?.unlockedLevelDepth ?? 0) >= 5 ? 'text-foreground' : 'text-muted-foreground'}`}>
                    L1-L5 {(user?.contributions?.unlockedLevelDepth ?? 0) >= 5 ? '已解锁' : '未解锁'}
                  </span>
                  <span className="text-muted-foreground">(直推≥1人认种)</span>
                </div>
                <div className="flex items-center gap-2">
                  {(user?.contributions?.unlockedLevelDepth ?? 0) >= 10 ? (
                    <span className="text-green-600">✓</span>
                  ) : (
                    <span className="text-muted-foreground">✗</span>
                  )}
                  <span className={`${(user?.contributions?.unlockedLevelDepth ?? 0) >= 10 ? 'text-foreground' : 'text-muted-foreground'}`}>
                    L6-L10 {(user?.contributions?.unlockedLevelDepth ?? 0) >= 10 ? '已解锁' : '未解锁'}
                  </span>
                  <span className="text-muted-foreground">(直推≥3人认种)</span>
                </div>
                <div className="flex items-center gap-2">
                  {(user?.contributions?.unlockedLevelDepth ?? 0) >= 15 ? (
                    <span className="text-green-600">✓</span>
                  ) : (
                    <span className="text-muted-foreground">✗</span>
                  )}
                  <span className={`${(user?.contributions?.unlockedLevelDepth ?? 0) >= 15 ? 'text-foreground' : 'text-muted-foreground'}`}>
                    L11-L15 {(user?.contributions?.unlockedLevelDepth ?? 0) >= 15 ? '已解锁' : '未解锁'}
                  </span>
                  <span className="text-muted-foreground">(直推≥5人认种)</span>
                </div>
              </div>
            </div>

            {/* 团队奖励 */}
            <div className="space-y-2">
              <div className="flex justify-between items-center">
                <span className="text-sm text-muted-foreground">团队奖励 (7.5%)</span>
                <span className="font-mono font-medium">{formatDecimal(user?.contributions?.teamBonus, 8)}</span>
              </div>
              <div className="pl-3 space-y-1 text-xs">
                <div className="flex items-center gap-2">
                  {(user?.contributions?.unlockedBonusTiers ?? 0) >= 1 ? (
                    <span className="text-green-600">✓</span>
                  ) : (
                    <span className="text-muted-foreground">✗</span>
                  )}
                  <span className={`${(user?.contributions?.unlockedBonusTiers ?? 0) >= 1 ? 'text-foreground' : 'text-muted-foreground'}`}>
                    第1档 2.5% {(user?.contributions?.unlockedBonusTiers ?? 0) >= 1 ? '已解锁' : '未解锁'}
                  </span>
                  <span className="text-muted-foreground">(自己认种)</span>
                </div>
                <div className="flex items-center gap-2">
                  {(user?.contributions?.unlockedBonusTiers ?? 0) >= 2 ? (
                    <span className="text-green-600">✓</span>
                  ) : (
                    <span className="text-muted-foreground">✗</span>
                  )}
                  <span className={`${(user?.contributions?.unlockedBonusTiers ?? 0) >= 2 ? 'text-foreground' : 'text-muted-foreground'}`}>
                    第2档 2.5% {(user?.contributions?.unlockedBonusTiers ?? 0) >= 2 ? '已解锁' : '未解锁'}
                  </span>
                  <span className="text-muted-foreground">(直推≥2人认种)</span>
                </div>
                <div className="flex items-center gap-2">
                  {(user?.contributions?.unlockedBonusTiers ?? 0) >= 3 ? (
                    <span className="text-green-600">✓</span>
                  ) : (
                    <span className="text-muted-foreground">✗</span>
                  )}
                  <span className={`${(user?.contributions?.unlockedBonusTiers ?? 0) >= 3 ? 'text-foreground' : 'text-muted-foreground'}`}>
                    第3档 2.5% {(user?.contributions?.unlockedBonusTiers ?? 0) >= 3 ? '已解锁' : '未解锁'}
                  </span>
                  <span className="text-muted-foreground">(直推≥4人认种)</span>
                </div>
              </div>
            </div>

            {/* 有效算力 */}
            <div className="flex justify-between pt-3 border-t font-medium">
              <span>有效算力 (贡献值)</span>
              <span className="font-mono text-primary text-lg">{formatDecimal(user?.effectiveContribution, 8)}</span>
            </div>

            {/* 解锁状态汇总 */}
            <div className="pt-2 border-t text-xs text-muted-foreground">
              <div className="flex justify-between">
                <span>直推认种人数</span>
                <span className="font-mono">{user?.contributions?.directReferralCount ?? 0} 人</span>
              </div>
              <div className="flex justify-between">
                <span>层级解锁深度</span>
                <span className="font-mono">{user?.contributions?.unlockedLevelDepth ?? 0} / 15 级</span>
              </div>
              <div className="flex justify-between">
                <span>奖励解锁档位</span>
                <span className="font-mono">{user?.contributions?.unlockedBonusTiers ?? 0} / 3 档</span>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 余额卡片 */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground flex items-center gap-1">
                  <Coins className="h-4 w-4" /> 挖矿余额
                </p>
                <p className="text-3xl font-bold font-mono text-primary mt-1">
                  {formatDecimal(user?.miningBalance, 8)}
                </p>
              </div>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground flex items-center gap-1">
                  <ShoppingCart className="h-4 w-4" /> 交易余额
                </p>
                <p className="text-3xl font-bold font-mono text-blue-600 mt-1">
                  {formatDecimal(user?.tradingBalance, 8)}
                </p>
              </div>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">冻结余额</p>
                <p className="text-3xl font-bold font-mono text-orange-600 mt-1">
                  {formatDecimal(user?.frozenBalance, 8)}
                </p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Tab 区域 */}
      <Tabs defaultValue="contributions">
        <TabsList className="grid w-full grid-cols-8">
          <TabsTrigger value="capabilities" className="flex items-center gap-1">
            <Shield className="h-4 w-4" />
            <span className="hidden sm:inline">权限管理</span>
          </TabsTrigger>
          <TabsTrigger value="contributions" className="flex items-center gap-1">
            <Zap className="h-4 w-4" />
            <span className="hidden sm:inline">算力记录</span>
          </TabsTrigger>
          <TabsTrigger value="referral" className="flex items-center gap-1">
            <Network className="h-4 w-4" />
            <span className="hidden sm:inline">引荐关系</span>
          </TabsTrigger>
          <TabsTrigger value="planting" className="flex items-center gap-1">
            <TreePine className="h-4 w-4" />
            <span className="hidden sm:inline">认种信息</span>
          </TabsTrigger>
          <TabsTrigger value="wallet" className="flex items-center gap-1">
            <Wallet className="h-4 w-4" />
            <span className="hidden sm:inline">钱包信息</span>
          </TabsTrigger>
          <TabsTrigger value="mining" className="flex items-center gap-1">
            <Coins className="h-4 w-4" />
            <span className="hidden sm:inline">挖矿记录</span>
          </TabsTrigger>
          <TabsTrigger value="batch-mining" className="flex items-center gap-1">
            <Gift className="h-4 w-4" />
            <span className="hidden sm:inline">批量补发</span>
          </TabsTrigger>
          <TabsTrigger value="trading" className="flex items-center gap-1">
            <ShoppingCart className="h-4 w-4" />
            <span className="hidden sm:inline">交易订单</span>
          </TabsTrigger>
        </TabsList>

        <TabsContent value="capabilities" className="mt-4">
          <CapabilityManagement accountSequence={accountSequence} />
        </TabsContent>

        <TabsContent value="contributions" className="mt-4">
          <ContributionRecordsList accountSequence={accountSequence} />
        </TabsContent>

        <TabsContent value="referral" className="mt-4">
          <ReferralTree accountSequence={accountSequence} />
        </TabsContent>

        <TabsContent value="planting" className="mt-4">
          <PlantingLedger accountSequence={accountSequence} />
        </TabsContent>

        <TabsContent value="wallet" className="mt-4">
          <WalletLedger accountSequence={accountSequence} />
        </TabsContent>

        <TabsContent value="mining" className="mt-4">
          <MiningRecordsList accountSequence={accountSequence} />
        </TabsContent>

        <TabsContent value="batch-mining" className="mt-4">
          <BatchMiningRecordsList accountSequence={accountSequence} />
        </TabsContent>

        <TabsContent value="trading" className="mt-4">
          <TradeOrdersList accountSequence={accountSequence} />
        </TabsContent>
      </Tabs>
    </div>
  );
}
