'use client';

import { useState, useRef } from 'react';
import { PageHeader } from '@/components/layout/page-header';
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 { Textarea } from '@/components/ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Skeleton } from '@/components/ui/skeleton';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
  Upload,
  FileSpreadsheet,
  Send,
  AlertCircle,
  CheckCircle2,
  Loader2,
  AlertTriangle,
  Ban,
  Eye,
} from 'lucide-react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { apiClient } from '@/lib/api/client';
import { useToast } from '@/lib/hooks/use-toast';

interface BatchItem {
  accountSequence: string;
  treeCount: number;
  miningStartDate: string;
  batch: number;
  preMineDays: number;
  remark?: string;
}

interface BatchPreviewUser {
  accountSequence: string;
  treeCount: number;
  preMineDays: number;
  userContribution: string;
  networkContribution: string;
  contributionRatio: string;
  totalSeconds: string;
  estimatedAmount: string;
}

interface BatchPreviewResult {
  canExecute: boolean;
  alreadyExecuted: boolean;
  totalBatches: number;
  totalUsers: number;
  batches: {
    batch: number;
    users: BatchPreviewUser[];
    batchTotalContribution: string;
    cumulativeNetworkContribution: string;
    batchTotalAmount: string;
  }[];
  grandTotalAmount: string;
  message: string;
  parsedItems?: BatchItem[];
  originalFileName?: string;
  calculatedStartDate?: string;  // 计算使用的起始日期 (YYYY-MM-DD)
}

interface BatchExecutionRecord {
  id: string;
  accountSequence: string;
  batch: number;
  treeCount: number;
  preMineDays: number;
  userContribution: string;
  networkContribution: string;
  contributionRatio: string;
  totalSeconds: string;
  amount: string;
  remark?: string;
  createdAt: string;
}

interface BatchExecution {
  id: string;
  operatorId: string;
  operatorName: string;
  reason: string;
  totalUsers: number;
  totalBatches: number;
  successCount: number;
  failedCount: number;
  totalAmount: string;
  executedAt: string;
  records: BatchExecutionRecord[];
}

export default function BatchMiningPage() {
  const queryClient = useQueryClient();
  const { toast } = useToast();
  const fileInputRef = useRef<HTMLInputElement>(null);

  const [previewResult, setPreviewResult] = useState<BatchPreviewResult | null>(null);
  const [parsedItems, setParsedItems] = useState<BatchItem[]>([]);
  const [fileName, setFileName] = useState<string>('');
  const [reason, setReason] = useState('');
  const [showConfirmDialog, setShowConfirmDialog] = useState(false);
  const [selectedBatch, setSelectedBatch] = useState<number | null>(null);

  // 获取批量补发状态
  const { data: statusData, isLoading: statusLoading } = useQuery({
    queryKey: ['batch-mining-status'],
    queryFn: async () => {
      console.log('[BatchMining] 开始获取批量补发状态...');
      try {
        const res = await apiClient.get('/batch-mining/status');
        console.log('[BatchMining] 状态响应:', res.data);
        // mining-admin-service 使用 TransformInterceptor 包装响应为 { success, data, timestamp }
        const data = res.data?.data || res.data;
        return data;
      } catch (error) {
        console.error('[BatchMining] 获取状态失败:', error);
        throw error;
      }
    },
  });

  // 获取执行记录（如果已执行）
  const { data: executionData, isLoading: executionLoading } = useQuery({
    queryKey: ['batch-mining-execution'],
    queryFn: async () => {
      console.log('[BatchMining] 开始获取执行记录...');
      try {
        const res = await apiClient.get('/batch-mining/execution');
        console.log('[BatchMining] 执行记录响应:', res.data);
        // mining-admin-service 使用 TransformInterceptor 包装响应为 { success, data, timestamp }
        const data = res.data?.data || res.data;
        return data as BatchExecution;
      } catch (error) {
        console.error('[BatchMining] 获取执行记录失败:', error);
        return null;
      }
    },
    enabled: statusData?.hasExecuted === true,
  });

  // 上传预览
  const uploadPreviewMutation = useMutation({
    mutationFn: async (file: File) => {
      console.log('[BatchMining] 开始上传文件预览:', file.name, '大小:', file.size);
      const formData = new FormData();
      formData.append('file', file);
      try {
        const res = await apiClient.post('/batch-mining/upload-preview', formData, {
          headers: { 'Content-Type': 'multipart/form-data' },
        });
        console.log('[BatchMining] 上传预览响应:', res.data);
        // mining-admin-service 使用 TransformInterceptor 包装响应为 { success, data, timestamp }
        const data = res.data?.data || res.data;
        return data as BatchPreviewResult;
      } catch (error: any) {
        console.error('[BatchMining] 上传预览失败:', error.response?.status, error.response?.data);
        throw error;
      }
    },
    onSuccess: (data) => {
      console.log('[BatchMining] 预览成功, 批次数:', data.totalBatches, '用户数:', data.totalUsers, '总金额:', data.grandTotalAmount);
      setPreviewResult(data);
      setParsedItems(data.parsedItems || []);
      setFileName(data.originalFileName || '');
      if (data.alreadyExecuted) {
        console.warn('[BatchMining] 批量补发已执行过');
        toast({ title: '批量补发已执行过，不能重复执行', variant: 'destructive' });
      }
    },
    onError: (error: any) => {
      console.error('[BatchMining] 上传预览 mutation 错误:', error);
      toast({ title: error.response?.data?.message || '上传失败', variant: 'destructive' });
      setPreviewResult(null);
      setParsedItems([]);
    },
  });

  // 执行补发
  const executeMutation = useMutation({
    mutationFn: async (data: { items: BatchItem[]; reason: string }) => {
      console.log('[BatchMining] 开始执行批量补发, 数据条数:', data.items.length, '原因:', data.reason);
      try {
        const res = await apiClient.post('/batch-mining/execute', data);
        console.log('[BatchMining] 执行响应:', res.data);
        // mining-admin-service 使用 TransformInterceptor 包装响应为 { success, data, timestamp }
        const result = res.data?.data || res.data;
        return result;
      } catch (error: any) {
        console.error('[BatchMining] 执行失败:', error.response?.status, error.response?.data);
        throw error;
      }
    },
    onSuccess: (data) => {
      console.log('[BatchMining] 执行成功, successCount:', data.successCount, 'totalAmount:', data.totalAmount);
      toast({
        title: `批量补发成功`,
        description: `成功 ${data.successCount} 个，总金额 ${parseFloat(data.totalAmount).toFixed(8)} 积分股`,
        variant: 'success' as any,
      });
      setShowConfirmDialog(false);
      setPreviewResult(null);
      setParsedItems([]);
      setFileName('');
      setReason('');
      queryClient.invalidateQueries({ queryKey: ['batch-mining-status'] });
      queryClient.invalidateQueries({ queryKey: ['batch-mining-execution'] });
    },
    onError: (error: any) => {
      console.error('[BatchMining] 执行 mutation 错误:', error);
      toast({ title: error.response?.data?.message || '执行失败', variant: 'destructive' });
    },
  });

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    console.log('[BatchMining] 文件选择事件触发');
    const file = e.target.files?.[0];
    if (file) {
      console.log('[BatchMining] 选中文件:', file.name, '大小:', file.size, '类型:', file.type);
      uploadPreviewMutation.mutate(file);
    } else {
      console.log('[BatchMining] 未选择文件');
    }
    // Reset input
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  const handleExecute = () => {
    console.log('[BatchMining] 点击执行按钮, 原因:', reason, '数据条数:', parsedItems.length);
    if (!reason.trim()) {
      console.warn('[BatchMining] 补发原因为空');
      toast({ title: '请输入补发原因', variant: 'destructive' });
      return;
    }
    console.log('[BatchMining] 开始调用执行 mutation...');
    executeMutation.mutate({ items: parsedItems, reason });
  };

  const formatNumber = (value: string | number) => {
    return parseFloat(String(value)).toLocaleString(undefined, { maximumFractionDigits: 8 });
  };

  const formatDateTime = (dateStr: string) => {
    return new Date(dateStr).toLocaleString('zh-CN');
  };

  const hasExecuted = statusData?.hasExecuted === true;

  return (
    <div className="space-y-6">
      <PageHeader
        title="批量补发挖矿"
        description="根据 Excel 文件批量为用户补发提前挖矿的收益（只能执行一次）"
      />

      {/* 状态提示 */}
      {statusLoading ? (
        <Skeleton className="h-20 w-full" />
      ) : hasExecuted ? (
        <Alert variant="destructive">
          <Ban className="h-4 w-4" />
          <AlertTitle>批量补发已执行</AlertTitle>
          <AlertDescription>
            批量补发已于 {executionData ? formatDateTime(executionData.executedAt) : '之前'} 执行完成，
            不能重复执行。操作人: {executionData?.operatorName}
          </AlertDescription>
        </Alert>
      ) : (
        <Alert>
          <AlertCircle className="h-4 w-4" />
          <AlertTitle>注意</AlertTitle>
          <AlertDescription>
            批量补发功能只能执行一次，请确保上传的 Excel 文件数据正确无误后再执行。
            建议先点击"预览"查看计算结果。
          </AlertDescription>
        </Alert>
      )}

      {/* 如果已执行，显示执行记录 */}
      {hasExecuted && executionData && (
        <Card>
          <CardHeader>
            <CardTitle className="text-lg flex items-center gap-2">
              <CheckCircle2 className="h-5 w-5 text-green-500" />
              执行记录
            </CardTitle>
            <CardDescription>
              总用户数: {executionData.totalUsers} | 成功: {executionData.successCount} |
              失败: {executionData.failedCount} | 总金额: {formatNumber(executionData.totalAmount)} 积分股
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="mb-4 p-4 bg-muted rounded-lg">
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                <div>
                  <span className="text-muted-foreground">执行时间:</span>
                  <span className="ml-2 font-medium">{formatDateTime(executionData.executedAt)}</span>
                </div>
                <div>
                  <span className="text-muted-foreground">操作人:</span>
                  <span className="ml-2 font-medium">{executionData.operatorName}</span>
                </div>
                <div>
                  <span className="text-muted-foreground">批次数:</span>
                  <span className="ml-2 font-medium">{executionData.totalBatches}</span>
                </div>
                <div>
                  <span className="text-muted-foreground">原因:</span>
                  <span className="ml-2 font-medium truncate" title={executionData.reason}>
                    {executionData.reason}
                  </span>
                </div>
              </div>
            </div>

            {executionLoading ? (
              <Skeleton className="h-64 w-full" />
            ) : (
              <div className="max-h-[500px] overflow-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>批次</TableHead>
                      <TableHead>注册ID</TableHead>
                      <TableHead>认种棵数</TableHead>
                      <TableHead>提前天数</TableHead>
                      <TableHead>用户算力</TableHead>
                      <TableHead>全网算力</TableHead>
                      <TableHead>补发金额</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {executionData.records.map((record) => (
                      <TableRow key={record.id}>
                        <TableCell>
                          <Badge variant="outline">批次 {record.batch}</Badge>
                        </TableCell>
                        <TableCell className="font-mono">{record.accountSequence}</TableCell>
                        <TableCell>{record.treeCount}</TableCell>
                        <TableCell>{record.preMineDays} 天</TableCell>
                        <TableCell className="font-mono text-xs">
                          {formatNumber(record.userContribution)}
                        </TableCell>
                        <TableCell className="font-mono text-xs">
                          {formatNumber(record.networkContribution)}
                        </TableCell>
                        <TableCell className="font-mono text-green-600">
                          {formatNumber(record.amount)}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* 如果未执行，显示上传区域 */}
      {!hasExecuted && (
        <>
          {/* 上传区域 */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center gap-2">
                <Upload className="h-5 w-5" />
                上传 Excel 文件
              </CardTitle>
              <CardDescription>
                上传包含用户批量补发数据的 Excel 文件（.xlsx），格式：序号 | 注册ID | 认种量 | 挖矿开始时间 | 批次 | 授权提前挖的天数 | 备注
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="flex items-center gap-4">
                <input
                  ref={fileInputRef}
                  type="file"
                  accept=".xlsx,.xls"
                  onChange={handleFileSelect}
                  className="hidden"
                />
                <Button
                  variant="outline"
                  onClick={() => fileInputRef.current?.click()}
                  disabled={uploadPreviewMutation.isPending}
                  className="w-full h-32 border-dashed"
                >
                  {uploadPreviewMutation.isPending ? (
                    <div className="flex flex-col items-center gap-2">
                      <Loader2 className="h-8 w-8 animate-spin" />
                      <span>解析中...</span>
                    </div>
                  ) : (
                    <div className="flex flex-col items-center gap-2">
                      <FileSpreadsheet className="h-8 w-8" />
                      <span>点击选择 Excel 文件</span>
                      <span className="text-xs text-muted-foreground">支持 .xlsx 格式</span>
                    </div>
                  )}
                </Button>
              </div>

              {fileName && (
                <div className="mt-4 flex items-center gap-2 text-sm">
                  <FileSpreadsheet className="h-4 w-4" />
                  <span>已选择: {fileName}</span>
                </div>
              )}
            </CardContent>
          </Card>

          {/* 预览结果 */}
          {previewResult && !previewResult.alreadyExecuted && previewResult.canExecute && (
            <Card>
              <CardHeader>
                <CardTitle className="text-lg flex items-center gap-2">
                  <Eye className="h-5 w-5" />
                  预览结果
                </CardTitle>
                <CardDescription>
                  共 {previewResult.totalBatches} 个批次，{previewResult.totalUsers} 个用户，
                  总补发金额: <span className="text-green-600 font-semibold">{formatNumber(previewResult.grandTotalAmount)}</span> 积分股
                  {previewResult.calculatedStartDate && (
                    <span className="ml-2 text-blue-600">
                      (从 {previewResult.calculatedStartDate} 开始计算)
                    </span>
                  )}
                </CardDescription>
              </CardHeader>
              <CardContent>
                <Tabs defaultValue={`batch-${previewResult.batches[0]?.batch || 1}`} className="w-full">
                  <TabsList className="flex flex-wrap h-auto gap-1 mb-4">
                    {previewResult.batches.map((batch) => (
                      <TabsTrigger
                        key={batch.batch}
                        value={`batch-${batch.batch}`}
                        className="text-xs"
                      >
                        批次 {batch.batch} ({batch.users.length}人)
                      </TabsTrigger>
                    ))}
                  </TabsList>

                  {previewResult.batches.map((batch) => (
                    <TabsContent key={batch.batch} value={`batch-${batch.batch}`}>
                      <div className="mb-4 p-4 bg-muted rounded-lg">
                        <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">{formatNumber(batch.batchTotalContribution)}</span>
                          </div>
                          <div>
                            <span className="text-muted-foreground">累计全网算力:</span>
                            <span className="ml-2 font-mono">{formatNumber(batch.cumulativeNetworkContribution)}</span>
                          </div>
                          <div>
                            <span className="text-muted-foreground">批次补发总额:</span>
                            <span className="ml-2 font-mono text-green-600">{formatNumber(batch.batchTotalAmount)}</span>
                          </div>
                        </div>
                      </div>

                      <div className="max-h-[400px] overflow-auto">
                        <Table>
                          <TableHeader>
                            <TableRow>
                              <TableHead>注册ID</TableHead>
                              <TableHead>认种棵数</TableHead>
                              <TableHead>提前天数</TableHead>
                              <TableHead>用户算力(70%)</TableHead>
                              <TableHead>算力占比</TableHead>
                              <TableHead>补发金额</TableHead>
                            </TableRow>
                          </TableHeader>
                          <TableBody>
                            {batch.users.map((user) => (
                              <TableRow key={user.accountSequence}>
                                <TableCell className="font-mono">{user.accountSequence}</TableCell>
                                <TableCell>{user.treeCount}</TableCell>
                                <TableCell>{user.preMineDays} 天</TableCell>
                                <TableCell className="font-mono text-xs">
                                  {formatNumber(user.userContribution)}
                                </TableCell>
                                <TableCell className="font-mono text-xs">
                                  {(parseFloat(user.contributionRatio) * 100).toFixed(6)}%
                                </TableCell>
                                <TableCell className="font-mono text-green-600">
                                  {formatNumber(user.estimatedAmount)}
                                </TableCell>
                              </TableRow>
                            ))}
                          </TableBody>
                        </Table>
                      </div>
                    </TabsContent>
                  ))}
                </Tabs>

                {/* 执行按钮 */}
                <div className="mt-6 p-6 bg-green-50 dark:bg-green-900/20 rounded-lg border border-green-200 dark:border-green-800">
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-sm text-green-600 dark:text-green-400">总补发金额</p>
                      <p className="text-3xl font-bold text-green-700 dark:text-green-300">
                        {formatNumber(previewResult.grandTotalAmount)} 积分股
                      </p>
                      <p className="text-sm text-muted-foreground mt-1">
                        {previewResult.totalBatches} 个批次，{previewResult.totalUsers} 个用户
                      </p>
                    </div>
                    <Button
                      size="lg"
                      onClick={() => setShowConfirmDialog(true)}
                      className="bg-green-600 hover:bg-green-700"
                    >
                      <Send className="h-4 w-4 mr-2" />
                      执行批量补发
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          )}
        </>
      )}

      {/* 确认对话框 */}
      <Dialog open={showConfirmDialog} onOpenChange={setShowConfirmDialog}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <AlertTriangle className="h-5 w-5 text-yellow-500" />
              确认执行批量补发
            </DialogTitle>
            <DialogDescription>
              此操作不可撤销，且只能执行一次。请仔细核对信息后再执行。
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-4">
            <div className="p-4 bg-muted rounded-lg space-y-2">
              <div className="flex justify-between">
                <span className="text-muted-foreground">总用户数</span>
                <span className="font-semibold">{previewResult?.totalUsers}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">批次数</span>
                <span className="font-semibold">{previewResult?.totalBatches}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">计算起始日期</span>
                <span className="font-semibold text-blue-600">{previewResult?.calculatedStartDate}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">总补发金额</span>
                <span className="font-mono font-semibold text-green-600">
                  {previewResult && formatNumber(previewResult.grandTotalAmount)} 积分股
                </span>
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="reason">补发原因（必填）</Label>
              <Textarea
                id="reason"
                placeholder="请输入补发原因，例如：2025年11月批次用户提前挖矿补发"
                value={reason}
                onChange={(e) => setReason(e.target.value)}
                rows={3}
              />
            </div>

            <Alert variant="destructive">
              <AlertTriangle className="h-4 w-4" />
              <AlertDescription>
                批量补发只能执行一次，请确保所有数据正确无误！
              </AlertDescription>
            </Alert>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowConfirmDialog(false)}>
              取消
            </Button>
            <Button
              onClick={handleExecute}
              disabled={executeMutation.isPending || !reason.trim()}
              className="bg-green-600 hover:bg-green-700"
            >
              {executeMutation.isPending ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  执行中...
                </>
              ) : (
                <>
                  <CheckCircle2 className="h-4 w-4 mr-2" />
                  确认执行
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
