'use client';

import { useState } from 'react';
import { PageHeader } from '@/components/layout/page-header';
import { useConfigs, useUpdateConfig, useTransferEnabled, useSetTransferEnabled, useMiningStatus, useActivateMining, useDeactivateMining } from '@/features/configs/hooks/use-configs';
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 { Switch } from '@/components/ui/switch';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Skeleton } from '@/components/ui/skeleton';
import { Badge } from '@/components/ui/badge';
import { Pencil, Save, X, Play, Pause, AlertCircle, CheckCircle2, Loader2 } from 'lucide-react';
import type { SystemConfig } from '@/types/config';

const categoryLabels: Record<string, string> = {
  mining: '挖矿配置',
  trading: '交易配置',
  distribution: '分配配置',
  system: '系统配置',
};

export default function ConfigsPage() {
  const { data: configs, isLoading } = useConfigs();
  const { data: transferEnabled, isLoading: transferLoading } = useTransferEnabled();
  const { data: miningStatus, isLoading: miningLoading } = useMiningStatus();
  const updateConfig = useUpdateConfig();
  const setTransferEnabled = useSetTransferEnabled();
  const activateMining = useActivateMining();
  const deactivateMining = useDeactivateMining();

  const [editingConfig, setEditingConfig] = useState<SystemConfig | null>(null);
  const [editValue, setEditValue] = useState('');

  const handleEdit = (config: SystemConfig) => {
    setEditingConfig(config);
    setEditValue(config.configValue);
  };

  const handleSave = () => {
    if (editingConfig) {
      updateConfig.mutate({ key: editingConfig.configKey, value: editValue });
      setEditingConfig(null);
    }
  };

  const handleTransferToggle = (checked: boolean) => {
    setTransferEnabled.mutate(checked);
  };

  const groupedConfigs = configs?.reduce(
    (acc, config) => {
      const category = config.category || 'system';
      if (!acc[category]) {
        acc[category] = [];
      }
      acc[category].push(config);
      return acc;
    },
    {} as Record<string, SystemConfig[]>
  );

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

  return (
    <div className="space-y-6">
      <PageHeader title="配置管理" description="管理系统配置参数" />

      {/* 挖矿状态卡片 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="text-lg">挖矿系统状态</CardTitle>
              <CardDescription>控制挖矿分配系统的运行状态</CardDescription>
            </div>
            {miningLoading ? (
              <Skeleton className="h-6 w-16" />
            ) : miningStatus?.error ? (
              <Badge variant="destructive" className="flex items-center gap-1">
                <AlertCircle className="h-3 w-3" />
                连接失败
              </Badge>
            ) : miningStatus?.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>
          {miningLoading ? (
            <Skeleton className="h-32 w-full" />
          ) : miningStatus?.error ? (
            <div className="text-center py-4 text-muted-foreground">
              <AlertCircle className="h-8 w-8 mx-auto mb-2 text-destructive" />
              <p>无法连接到挖矿服务</p>
              <p className="text-sm">{miningStatus.error}</p>
            </div>
          ) : !miningStatus?.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">请运行 seed 脚本初始化挖矿配置</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">第 {miningStatus.currentEra} 时代</p>
                </div>
                <div className="space-y-1">
                  <p className="text-sm text-muted-foreground">剩余分配量</p>
                  <p className="text-lg font-semibold">{formatNumber(miningStatus.remainingDistribution)}</p>
                </div>
                <div className="space-y-1">
                  <p className="text-sm text-muted-foreground">每秒分配</p>
                  <p className="text-lg font-semibold">{formatNumber(miningStatus.secondDistribution)}</p>
                </div>
                <div className="space-y-1">
                  <p className="text-sm text-muted-foreground">挖矿账户数</p>
                  <p className="text-lg font-semibold">{miningStatus.accountCount}</p>
                </div>
              </div>

              {/* 算力同步状态提示 */}
              {miningStatus.contributionSyncStatus && !miningStatus.contributionSyncStatus.isSynced && (
                <div className="flex items-center gap-2 p-3 bg-yellow-50 dark:bg-yellow-900/20 rounded-lg border border-yellow-200 dark:border-yellow-800">
                  <Loader2 className="h-4 w-4 animate-spin text-yellow-600" />
                  <div className="flex-1">
                    <p className="text-sm font-medium text-yellow-800 dark:text-yellow-200">全网算力同步中...</p>
                    <p className="text-xs text-yellow-600 dark:text-yellow-400">
                      mining-service 全网理论算力: {formatNumber(miningStatus.contributionSyncStatus.miningNetworkTotal)} /
                      contribution-service 全网理论算力: {formatNumber(miningStatus.contributionSyncStatus.networkTotalContribution)}
                    </p>
                  </div>
                </div>
              )}

              <div className="flex justify-end pt-4 border-t">
                {miningStatus.isActive ? (
                  <Button
                    variant="destructive"
                    onClick={() => deactivateMining.mutate()}
                    disabled={deactivateMining.isPending}
                  >
                    <Pause className="h-4 w-4 mr-2" />
                    {deactivateMining.isPending ? '停用中...' : '停用挖矿'}
                  </Button>
                ) : (
                  <Button
                    onClick={() => activateMining.mutate()}
                    disabled={activateMining.isPending || (miningStatus.contributionSyncStatus && !miningStatus.contributionSyncStatus.isSynced)}
                  >
                    {miningStatus.contributionSyncStatus && !miningStatus.contributionSyncStatus.isSynced ? (
                      <>
                        <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                        全网算力同步中...
                      </>
                    ) : (
                      <>
                        <Play className="h-4 w-4 mr-2" />
                        {activateMining.isPending ? '激活中...' : '激活挖矿'}
                      </>
                    )}
                  </Button>
                )}
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="text-lg">划转开关</CardTitle>
          <CardDescription>控制用户是否可以进行挖矿账户到交易账户的划转</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-between">
            <div>
              <p className="font-medium">允许用户划转</p>
              <p className="text-sm text-muted-foreground">开启后用户可以将挖矿获得的积分股划转到交易账户</p>
            </div>
            {transferLoading ? (
              <Skeleton className="h-6 w-11" />
            ) : (
              <Switch
                checked={transferEnabled}
                onCheckedChange={handleTransferToggle}
                disabled={setTransferEnabled.isPending}
              />
            )}
          </div>
        </CardContent>
      </Card>

      {isLoading ? (
        <Card>
          <CardContent className="p-6">
            <Skeleton className="h-64 w-full" />
          </CardContent>
        </Card>
      ) : (
        Object.entries(groupedConfigs || {}).map(([category, configs]) => (
          <Card key={category}>
            <CardHeader>
              <CardTitle className="text-lg">{categoryLabels[category] || category}</CardTitle>
            </CardHeader>
            <CardContent className="p-0">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>配置项</TableHead>
                    <TableHead>描述</TableHead>
                    <TableHead>当前值</TableHead>
                    <TableHead className="w-[100px]">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {configs.map((config) => (
                    <TableRow key={config.configKey}>
                      <TableCell className="font-mono">{config.configKey}</TableCell>
                      <TableCell className="text-muted-foreground">{config.description}</TableCell>
                      <TableCell className="font-mono">{config.configValue}</TableCell>
                      <TableCell>
                        {config.isEditable && (
                          <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => handleEdit(config)}>
                            <Pencil className="h-4 w-4" />
                          </Button>
                        )}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        ))
      )}

      <Dialog open={!!editingConfig} onOpenChange={() => setEditingConfig(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>编辑配置</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>配置项</Label>
              <Input value={editingConfig?.configKey || ''} disabled />
            </div>
            <div className="space-y-2">
              <Label>描述</Label>
              <p className="text-sm text-muted-foreground">{editingConfig?.description}</p>
            </div>
            <div className="space-y-2">
              <Label>配置值</Label>
              <Input value={editValue} onChange={(e) => setEditValue(e.target.value)} />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setEditingConfig(null)}>
              <X className="h-4 w-4 mr-2" />
              取消
            </Button>
            <Button onClick={handleSave} disabled={updateConfig.isPending}>
              <Save className="h-4 w-4 mr-2" />
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
