'use client';

import { useState } 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 { Input } from '@/components/ui/input';
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 } from '@/components/ui/alert';
import { Calculator, Send, AlertCircle, CheckCircle2, Loader2, History } 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 CalculateResult {
  accountSequence: string;
  adoptionDate: string;
  effectiveDate: string;
  totalSeconds: string;
  userContribution: string;
  networkContribution: string;
  secondDistribution: string;
  contributionRatio: string;
  estimatedAmount: string;
  alreadyProcessed: boolean;
}

interface ManualMiningRecord {
  id: string;
  accountSequence: string;
  adoptionDate: string;
  effectiveDate: string;
  executeDate: string;
  totalSeconds: string;
  amount: string;
  operatorId: string;
  operatorName: string;
  reason: string;
  walletSynced: boolean;
  walletSyncedAt: string | null;
  createdAt: string;
}

export default function ManualMiningPage() {
  const queryClient = useQueryClient();
  const { toast } = useToast();
  const [accountSequence, setAccountSequence] = useState('');
  const [adoptionDate, setAdoptionDate] = useState('');
  const [reason, setReason] = useState('');
  const [calculateResult, setCalculateResult] = useState<CalculateResult | null>(null);
  const [showConfirmDialog, setShowConfirmDialog] = useState(false);

  // 获取记录列表
  const { data: recordsData, isLoading: recordsLoading } = useQuery({
    queryKey: ['manual-mining-records'],
    queryFn: async () => {
      const res = await apiClient.get('/manual-mining/records');
      return res.data;
    },
  });

  // 计算预估金额
  const calculateMutation = useMutation({
    mutationFn: async (data: { accountSequence: string; adoptionDate: string }) => {
      const res = await apiClient.post('/manual-mining/calculate', data);
      return res.data;
    },
    onSuccess: (data) => {
      setCalculateResult(data);
      if (data.alreadyProcessed) {
        toast({ title: '该用户已补发过挖矿收益', variant: 'destructive' });
      }
    },
    onError: (error: any) => {
      toast({ title: error.response?.data?.message || '计算失败', variant: 'destructive' });
      setCalculateResult(null);
    },
  });

  // 执行补发
  const executeMutation = useMutation({
    mutationFn: async (data: { accountSequence: string; adoptionDate: string; reason: string }) => {
      const res = await apiClient.post('/manual-mining/execute', data);
      return res.data;
    },
    onSuccess: (data) => {
      toast({ title: `成功补发 ${parseFloat(data.amount).toFixed(8)} 积分股`, variant: 'success' as any });
      setShowConfirmDialog(false);
      setCalculateResult(null);
      setAccountSequence('');
      setAdoptionDate('');
      setReason('');
      queryClient.invalidateQueries({ queryKey: ['manual-mining-records'] });
    },
    onError: (error: any) => {
      toast({ title: error.response?.data?.message || '执行失败', variant: 'destructive' });
    },
  });

  const handleCalculate = () => {
    if (!accountSequence || !adoptionDate) {
      toast({ title: '请输入账户序列号和认种日期', variant: 'destructive' });
      return;
    }
    calculateMutation.mutate({ accountSequence, adoptionDate });
  };

  const handleExecute = () => {
    if (!reason.trim()) {
      toast({ title: '请输入补发原因', variant: 'destructive' });
      return;
    }
    executeMutation.mutate({ accountSequence, adoptionDate, reason });
  };

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

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

  return (
    <div className="space-y-6">
      <PageHeader
        title="手工补发挖矿"
        description="为从1.0系统同步的用户手工补发历史挖矿收益"
      />

      {/* 补发表单 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg flex items-center gap-2">
            <Calculator className="h-5 w-5" />
            计算补发金额
          </CardTitle>
          <CardDescription>
            输入用户账户序列号和认种日期，系统将根据当前算力和挖矿配置计算补发金额
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="accountSequence">账户序列号</Label>
              <Input
                id="accountSequence"
                placeholder="例如: U123456"
                value={accountSequence}
                onChange={(e) => setAccountSequence(e.target.value)}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="adoptionDate">认种日期</Label>
              <Input
                id="adoptionDate"
                type="date"
                value={adoptionDate}
                onChange={(e) => setAdoptionDate(e.target.value)}
              />
            </div>
          </div>

          <Button
            onClick={handleCalculate}
            disabled={calculateMutation.isPending || !accountSequence || !adoptionDate}
          >
            {calculateMutation.isPending ? (
              <>
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                计算中...
              </>
            ) : (
              <>
                <Calculator className="h-4 w-4 mr-2" />
                计算预估金额
              </>
            )}
          </Button>

          {/* 计算结果 */}
          {calculateResult && (
            <div className="mt-6 space-y-4">
              {calculateResult.alreadyProcessed ? (
                <Alert variant="destructive">
                  <AlertCircle className="h-4 w-4" />
                  <AlertDescription>
                    该用户已补发过挖矿收益，金额: {formatNumber(calculateResult.estimatedAmount)} 积分股
                  </AlertDescription>
                </Alert>
              ) : (
                <>
                  <div className="p-4 bg-muted rounded-lg">
                    <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="font-semibold">{calculateResult.effectiveDate}</p>
                      </div>
                      <div className="space-y-1">
                        <p className="text-sm text-muted-foreground">补发秒数</p>
                        <p className="font-semibold">{parseInt(calculateResult.totalSeconds).toLocaleString()}</p>
                      </div>
                      <div className="space-y-1">
                        <p className="text-sm text-muted-foreground">用户算力</p>
                        <p className="font-semibold">{formatNumber(calculateResult.userContribution)}</p>
                      </div>
                      <div className="space-y-1">
                        <p className="text-sm text-muted-foreground">算力占比</p>
                        <p className="font-semibold">
                          {(parseFloat(calculateResult.contributionRatio) * 100).toFixed(6)}%
                        </p>
                      </div>
                    </div>
                  </div>

                  <div className="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(calculateResult.estimatedAmount)} 积分股
                        </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>
                </>
              )}
            </div>
          )}
        </CardContent>
      </Card>

      {/* 补发记录列表 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg flex items-center gap-2">
            <History className="h-5 w-5" />
            补发记录
          </CardTitle>
          <CardDescription>已执行的手工补发记录列表</CardDescription>
        </CardHeader>
        <CardContent className="p-0">
          {recordsLoading ? (
            <div className="p-6">
              <Skeleton className="h-64 w-full" />
            </div>
          ) : recordsData?.items?.length === 0 ? (
            <div className="p-6 text-center text-muted-foreground">
              暂无补发记录
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>账户序列号</TableHead>
                  <TableHead>认种日期</TableHead>
                  <TableHead>补发金额</TableHead>
                  <TableHead>操作人</TableHead>
                  <TableHead>原因</TableHead>
                  <TableHead>钱包同步</TableHead>
                  <TableHead>执行时间</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {recordsData?.items?.map((record: ManualMiningRecord) => (
                  <TableRow key={record.id}>
                    <TableCell className="font-mono">{record.accountSequence}</TableCell>
                    <TableCell>{record.adoptionDate}</TableCell>
                    <TableCell className="font-mono">{formatNumber(record.amount)}</TableCell>
                    <TableCell>{record.operatorName}</TableCell>
                    <TableCell className="max-w-[200px] truncate" title={record.reason}>
                      {record.reason}
                    </TableCell>
                    <TableCell>
                      {record.walletSynced ? (
                        <Badge variant="default" className="bg-green-500">
                          <CheckCircle2 className="h-3 w-3 mr-1" />
                          已同步
                        </Badge>
                      ) : (
                        <Badge variant="secondary">
                          <Loader2 className="h-3 w-3 mr-1 animate-spin" />
                          同步中
                        </Badge>
                      )}
                    </TableCell>
                    <TableCell>{formatDateTime(record.executeDate)}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      {/* 确认对话框 */}
      <Dialog open={showConfirmDialog} onOpenChange={setShowConfirmDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>确认执行补发</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-mono font-semibold">{accountSequence}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">认种日期</span>
                <span className="font-semibold">{adoptionDate}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">补发金额</span>
                <span className="font-mono font-semibold text-green-600">
                  {calculateResult && formatNumber(calculateResult.estimatedAmount)} 积分股
                </span>
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="reason">补发原因（必填）</Label>
              <Textarea
                id="reason"
                placeholder="请输入补发原因，例如：1.0系统同步延迟补发"
                value={reason}
                onChange={(e) => setReason(e.target.value)}
                rows={3}
              />
            </div>

            <Alert>
              <AlertCircle 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>
  );
}
