'use client';

import { useState } from 'react';
import { PageHeader } from '@/components/layout/page-header';
import {
  useTradingStatus,
  useActivateTrading,
  useDeactivateTrading,
  useBuyEnabled,
  useSetBuyEnabled,
  useBurnStatus,
  useBurnRecords,
  useMarketOverview,
} from '@/features/trading/hooks/use-trading';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } 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 { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import {
  Play,
  Pause,
  AlertCircle,
  CheckCircle2,
  TrendingUp,
  Flame,
  DollarSign,
  Activity,
  RefreshCw,
  ShoppingCart,
} from 'lucide-react';
import { Switch } from '@/components/ui/switch';
import { formatDistanceToNow } from 'date-fns';
import { zhCN } from 'date-fns/locale';

export default function TradingPage() {
  const { data: tradingStatus, isLoading: tradingLoading, refetch: refetchTrading } = useTradingStatus();
  const { data: burnStatus, isLoading: burnLoading, refetch: refetchBurn } = useBurnStatus();
  const { data: marketOverview, isLoading: marketLoading, refetch: refetchMarket } = useMarketOverview();
  const { data: buyEnabledData, isLoading: buyEnabledLoading } = useBuyEnabled();
  const activateTrading = useActivateTrading();
  const deactivateTrading = useDeactivateTrading();
  const setBuyEnabled = useSetBuyEnabled();

  const [recordsPage, setRecordsPage] = useState(1);
  const [recordsFilter, setRecordsFilter] = useState<'ALL' | 'MINUTE_BURN' | 'SELL_BURN'>('ALL');
  const { data: burnRecords, isLoading: recordsLoading } = useBurnRecords(
    recordsPage,
    20,
    recordsFilter === 'ALL' ? undefined : recordsFilter
  );

  const formatNumber = (value: string | undefined, decimals: number = 2) => {
    if (!value) return '0';
    const num = parseFloat(value);
    if (isNaN(num)) return '0';
    return num.toLocaleString(undefined, { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
  };

  const formatPrice = (value: string | undefined) => {
    if (!value) return '0';
    const num = parseFloat(value);
    if (isNaN(num)) return '0';
    return num.toFixed(18);
  };

  const handleRefresh = () => {
    refetchTrading();
    refetchBurn();
    refetchMarket();
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <PageHeader title="交易系统管理" description="管理交易/销毁系统的运行状态" />
        <Button variant="outline" size="sm" onClick={handleRefresh}>
          <RefreshCw className="h-4 w-4 mr-2" />
          刷新
        </Button>
      </div>

      {/* 交易系统状态卡片 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="text-lg flex items-center gap-2">
                <Activity className="h-5 w-5" />
                交易系统状态
              </CardTitle>
              <CardDescription>控制交易和每分钟自动销毁的运行状态</CardDescription>
            </div>
            {tradingLoading ? (
              <Skeleton className="h-6 w-16" />
            ) : !tradingStatus?.initialized ? (
              <Badge variant="secondary" className="flex items-center gap-1">
                <AlertCircle className="h-3 w-3" />
                未初始化
              </Badge>
            ) : tradingStatus?.isActive ? (
              <Badge variant="default" className="flex items-center gap-1 bg-green-500">
                <CheckCircle2 className="h-3 w-3" />
                运行中
              </Badge>
            ) : (
              <Badge variant="secondary" className="flex items-center gap-1">
                <Pause className="h-3 w-3" />
                已停用
              </Badge>
            )}
          </div>
        </CardHeader>
        <CardContent>
          {tradingLoading ? (
            <Skeleton className="h-32 w-full" />
          ) : !tradingStatus?.initialized ? (
            <div className="text-center py-4 text-muted-foreground">
              <AlertCircle className="h-8 w-8 mx-auto mb-2 text-yellow-500" />
              <p>交易系统未初始化</p>
              <p className="text-sm">请确保 trading-service 已正常启动</p>
            </div>
          ) : (
            <div className="space-y-4">
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div className="space-y-1">
                  <p className="text-sm text-muted-foreground">总积分股</p>
                  <p className="text-lg font-semibold">{formatNumber(tradingStatus.totalShares, 0)}</p>
                </div>
                <div className="space-y-1">
                  <p className="text-sm text-muted-foreground">销毁目标</p>
                  <p className="text-lg font-semibold">{formatNumber(tradingStatus.burnTarget, 0)}</p>
                </div>
                <div className="space-y-1">
                  <p className="text-sm text-muted-foreground">销毁周期</p>
                  <p className="text-lg font-semibold">{tradingStatus.burnPeriodMinutes?.toLocaleString()} 分钟</p>
                </div>
                <div className="space-y-1">
                  <p className="text-sm text-muted-foreground">每分钟销毁率</p>
                  <p className="text-lg font-semibold">{formatNumber(tradingStatus.minuteBurnRate, 8)}</p>
                </div>
              </div>

              {tradingStatus.activatedAt && (
                <div className="pt-2">
                  <p className="text-sm text-muted-foreground">
                    激活时间: {new Date(tradingStatus.activatedAt).toLocaleString()} (
                    {formatDistanceToNow(new Date(tradingStatus.activatedAt), { addSuffix: true, locale: zhCN })})
                  </p>
                </div>
              )}

              <div className="flex justify-end pt-4 border-t">
                {tradingStatus.isActive ? (
                  <Button
                    variant="destructive"
                    onClick={() => deactivateTrading.mutate()}
                    disabled={deactivateTrading.isPending}
                  >
                    <Pause className="h-4 w-4 mr-2" />
                    {deactivateTrading.isPending ? '停用中...' : '停用交易系统'}
                  </Button>
                ) : (
                  <Button onClick={() => activateTrading.mutate()} disabled={activateTrading.isPending}>
                    <Play className="h-4 w-4 mr-2" />
                    {activateTrading.isPending ? '激活中...' : '激活交易系统'}
                  </Button>
                )}
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 买入功能开关 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="text-lg flex items-center gap-2">
                <ShoppingCart className="h-5 w-5" />
                买入功能开关
              </CardTitle>
              <CardDescription>控制用户是否可以在App中使用买入功能</CardDescription>
            </div>
            {buyEnabledLoading ? (
              <Skeleton className="h-6 w-16" />
            ) : buyEnabledData?.enabled ? (
              <Badge variant="default" className="flex items-center gap-1 bg-green-500">
                <CheckCircle2 className="h-3 w-3" />
                已开启
              </Badge>
            ) : (
              <Badge variant="secondary" className="flex items-center gap-1">
                <Pause className="h-3 w-3" />
                已关闭
              </Badge>
            )}
          </div>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-between p-4 bg-muted rounded-lg">
            <div className="space-y-1">
              <p className="font-medium">买入功能</p>
              <p className="text-sm text-muted-foreground">
                {buyEnabledData?.enabled
                  ? '用户可以在兑换页面使用买入功能购买积分股'
                  : '买入功能已关闭，用户在兑换页面将看到"待开启"提示'}
              </p>
            </div>
            <Switch
              checked={buyEnabledData?.enabled ?? false}
              onCheckedChange={(checked) => setBuyEnabled.mutate(checked)}
              disabled={setBuyEnabled.isPending || buyEnabledLoading}
            />
          </div>
        </CardContent>
      </Card>

      {/* 市场概览和销毁进度 */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* 市场概览 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg flex items-center gap-2">
              <TrendingUp className="h-5 w-5" />
              市场概览
            </CardTitle>
          </CardHeader>
          <CardContent>
            {marketLoading ? (
              <Skeleton className="h-40 w-full" />
            ) : !marketOverview ? (
              <div className="text-center py-4 text-muted-foreground">
                <p>无法获取市场数据</p>
              </div>
            ) : (
              <div className="space-y-4">
                <div className="flex items-center justify-between p-3 bg-muted rounded-lg">
                  <div className="flex items-center gap-2">
                    <DollarSign className="h-5 w-5 text-green-500" />
                    <span className="text-sm text-muted-foreground">当前积分股价格</span>
                  </div>
                  <span className="font-mono text-lg font-semibold">{formatPrice(marketOverview.price)}</span>
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-1">
                    <p className="text-sm text-muted-foreground">绿积分</p>
                    <p className="font-semibold">{formatNumber(marketOverview.greenPoints, 8)}</p>
                  </div>
                  <div className="space-y-1">
                    <p className="text-sm text-muted-foreground">流通池</p>
                    <p className="font-semibold">{formatNumber(marketOverview.circulationPool, 8)}</p>
                  </div>
                  <div className="space-y-1">
                    <p className="text-sm text-muted-foreground">有效分母</p>
                    <p className="font-semibold">{formatNumber(marketOverview.effectiveDenominator, 0)}</p>
                  </div>
                  <div className="space-y-1">
                    <p className="text-sm text-muted-foreground">销毁倍数</p>
                    <p className="font-semibold">{formatNumber(marketOverview.burnMultiplier, 8)}</p>
                  </div>
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* 销毁进度 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-lg flex items-center gap-2">
              <Flame className="h-5 w-5 text-orange-500" />
              销毁进度
            </CardTitle>
          </CardHeader>
          <CardContent>
            {burnLoading ? (
              <Skeleton className="h-40 w-full" />
            ) : !burnStatus ? (
              <div className="text-center py-4 text-muted-foreground">
                <p>无法获取销毁数据</p>
              </div>
            ) : (
              <div className="space-y-4">
                <div className="space-y-2">
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">销毁进度</span>
                    <span className="font-semibold">{formatNumber(burnStatus.burnProgress, 4)}%</span>
                  </div>
                  <div className="w-full bg-muted rounded-full h-3">
                    <div
                      className="bg-orange-500 h-3 rounded-full transition-all"
                      style={{ width: `${Math.min(parseFloat(burnStatus.burnProgress), 100)}%` }}
                    />
                  </div>
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-1">
                    <p className="text-sm text-muted-foreground">已销毁</p>
                    <p className="font-semibold text-orange-500">{formatNumber(burnStatus.totalBurned, 8)}</p>
                  </div>
                  <div className="space-y-1">
                    <p className="text-sm text-muted-foreground">剩余目标</p>
                    <p className="font-semibold">{formatNumber(burnStatus.remainingBurn, 8)}</p>
                  </div>
                  <div className="space-y-1">
                    <p className="text-sm text-muted-foreground">剩余分钟</p>
                    <p className="font-semibold">{burnStatus.remainingMinutes?.toLocaleString()}</p>
                  </div>
                  <div className="space-y-1">
                    <p className="text-sm text-muted-foreground">每分钟销毁</p>
                    <p className="font-semibold">{formatNumber(burnStatus.minuteBurnRate, 8)}</p>
                  </div>
                </div>
                {burnStatus.lastBurnMinute && (
                  <p className="text-sm text-muted-foreground pt-2 border-t">
                    最后销毁: {new Date(burnStatus.lastBurnMinute).toLocaleString()}
                  </p>
                )}
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* 销毁记录 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="text-lg">销毁记录</CardTitle>
            <Select
              value={recordsFilter}
              onValueChange={(value) => {
                setRecordsFilter(value as 'ALL' | 'MINUTE_BURN' | 'SELL_BURN');
                setRecordsPage(1);
              }}
            >
              <SelectTrigger className="w-[150px]">
                <SelectValue placeholder="筛选类型" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="ALL">全部</SelectItem>
                <SelectItem value="MINUTE_BURN">每分钟销毁</SelectItem>
                <SelectItem value="SELL_BURN">卖出销毁</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardHeader>
        <CardContent className="p-0">
          {recordsLoading ? (
            <div className="p-6">
              <Skeleton className="h-64 w-full" />
            </div>
          ) : !burnRecords?.data?.length ? (
            <div className="text-center py-8 text-muted-foreground">
              <p>暂无销毁记录</p>
            </div>
          ) : (
            <>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>时间</TableHead>
                    <TableHead>类型</TableHead>
                    <TableHead>销毁量</TableHead>
                    <TableHead>剩余目标</TableHead>
                    <TableHead>来源账户</TableHead>
                    <TableHead>备注</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {burnRecords.data.map((record) => (
                    <TableRow key={record.id}>
                      <TableCell className="font-mono text-sm">
                        {new Date(record.burnMinute).toLocaleString()}
                      </TableCell>
                      <TableCell>
                        <Badge variant={record.sourceType === 'MINUTE_BURN' ? 'secondary' : 'default'}>
                          {record.sourceType === 'MINUTE_BURN' ? '自动销毁' : '卖出销毁'}
                        </Badge>
                      </TableCell>
                      <TableCell className="font-mono">{formatNumber(record.burnAmount, 8)}</TableCell>
                      <TableCell className="font-mono">{formatNumber(record.remainingTarget, 0)}</TableCell>
                      <TableCell className="font-mono text-sm">
                        {record.sourceAccountSeq || '-'}
                      </TableCell>
                      <TableCell className="text-sm text-muted-foreground max-w-[200px] truncate">
                        {record.memo || '-'}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
              <div className="flex items-center justify-between px-4 py-3 border-t">
                <p className="text-sm text-muted-foreground">共 {burnRecords.total} 条记录</p>
                <div className="flex gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    disabled={recordsPage <= 1}
                    onClick={() => setRecordsPage((p) => p - 1)}
                  >
                    上一页
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    disabled={burnRecords.data.length < 20}
                    onClick={() => setRecordsPage((p) => p + 1)}
                  >
                    下一页
                  </Button>
                </div>
              </div>
            </>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
