/**
 * filekorolheader: 外部数据源管理页面 - 多源数据接入管理中心
 * 功能：外部数据源管理、数据质量监控、异常告警处理、数据接入配置
 * 路径：/ai-crop-model/data-sense-center/external
 * 规范：遵循crop-x/docs/开发项目规范.md，使用useState状态管理，shadcn语义化样式
 */
'use client';

import { useState, useEffect } from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Progress } from '@/components/ui/progress';
import { Switch } from '@/components/ui/switch';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import {
  Database,
  Plus,
  Upload,
  RefreshCw,
  CheckCircle,
  XCircle,
  AlertCircle,
  Clock,
  Cloud,
  Satellite,
  Wifi,
  WifiOff,
  Activity,
  Thermometer,
  Droplet,
  Sun,
  Wind,
  Camera,
  Gauge,
  Zap,
  Settings,
  Eye,
  Edit,
  Trash2,
  Link,
  PlayCircle,
  PauseCircle,
  BarChart3,
  Calendar,
  MapPin,
  Signal,
  CheckCircle2,
  AlertTriangle,
  TrendingUp,
  Filter,
  FileText,
  Search,
  Download,
} from 'lucide-react';
import { toast } from 'sonner';

type DataSourceType = '气象数据' | '卫星遥感' | '土壤数据' | '作物生长' | '其他';
type DataSourceStatus = '正常' | '异常' | '离线' | '待配置';
type AccessMethod = '手动上传' | 'API对接' | 'FTP传输' | 'WebSocket';

interface ExternalDataSource {
  id: string;
  name: string;
  type: DataSourceType;
  provider: string;
  accessMethod: AccessMethod;
  apiEndpoint?: string;
  updateFrequency: string;
  lastUpdateTime: string;
  dataPoints: number;
  status: DataSourceStatus;
  dataFields: string[];
  description: string;
}

interface DataQuality {
  completeness: number;
  accuracy: number;
  timeliness: number;
  consistency: number;
}

export default function ExternalPage() {
  const [activeTab, setActiveTab] = useState('external');
  const [showDataSourceDialog, setShowDataSourceDialog] = useState(false);
  const [showUploadDialog, setShowUploadDialog] = useState(false);
  const [showValidationDialog, setShowValidationDialog] = useState(false);
  const [showDataPreviewDialog, setShowDataPreviewDialog] = useState(false);
  const [selectedDataSource, setSelectedDataSource] = useState<ExternalDataSource | null>(null);
  const [uploadedFile, setUploadedFile] = useState<File | null>(null);
  const [uploadedFiles, setUploadedFiles] = useState<File[]>([]);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [selectedAccessMethod, setSelectedAccessMethod] = useState<AccessMethod>('API对接');
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedType, setSelectedType] = useState<string>('all');
  const [selectedStatus, setSelectedStatus] = useState<string>('all');

  // 外部数据源模拟数据
  const [externalDataSources] = useState<ExternalDataSource[]>([
    {
      id: 'ext-1',
      name: '国家气象局API',
      type: '气象数据',
      provider: '中国气象局',
      accessMethod: 'API对接',
      apiEndpoint: 'https://api.weather.gov.cn/v1/data',
      updateFrequency: '每小时',
      lastUpdateTime: '2024-10-15 14:00:00',
      dataPoints: 24850,
      status: '正常',
      dataFields: ['温度', '湿度', '气压', '降水量', '风速', '风向'],
      description: '实时气象数据，包含温度、湿度、降水等多维度信息',
    },
    {
      id: 'ext-2',
      name: 'Sentinel-2卫星数据',
      type: '卫星遥感',
      provider: 'ESA欧空局',
      accessMethod: 'API对接',
      apiEndpoint: 'https://scihub.copernicus.eu/dhus',
      updateFrequency: '每5天',
      lastUpdateTime: '2024-10-12 08:30:00',
      dataPoints: 1280,
      status: '正常',
      dataFields: ['NDVI', 'EVI', 'LAI', '地表温度', '土壤湿度指数'],
      description: '高分辨率卫星遥感影像，用于作物长势监测',
    },
    {
      id: 'ext-3',
      name: '土壤数据库',
      type: '土壤数据',
      provider: '农业部土壤监测中心',
      accessMethod: '手动上传',
      updateFrequency: '每季度',
      lastUpdateTime: '2024-09-20 10:15:00',
      dataPoints: 385,
      status: '正常',
      dataFields: ['pH值', '有机质', '氮磷钾含量', '土壤质地', '盐分'],
      description: '区域土壤理化性质数据',
    },
    {
      id: 'ext-4',
      name: '光照辐射数据',
      type: '气象数据',
      provider: '光伏气象站网络',
      accessMethod: 'FTP传输',
      updateFrequency: '每30分钟',
      lastUpdateTime: '2024-10-15 13:30:00',
      dataPoints: 15620,
      status: '正常',
      dataFields: ['总辐射', '直接辐射', '散射辐射', '光合有效辐射'],
      description: '太阳辐射数据，用于光合作用分析',
    },
    {
      id: 'ext-5',
      name: '作物生长监测',
      type: '作物生长',
      provider: '农业科学院',
      accessMethod: 'API对接',
      updateFrequency: '每周',
      lastUpdateTime: '2024-10-14 09:00:00',
      dataPoints: 2450,
      status: '异常',
      dataFields: ['株高', '叶面积指数', '生物量', '产量预测'],
      description: '作物生长参数动态监测数据',
    },
  ]);

  // 数据质量评估
  const [dataQuality] = useState<DataQuality>({
    completeness: 94.5,
    accuracy: 96.8,
    timeliness: 92.3,
    consistency: 95.2,
  });

  // 统计数据
  const totalExternalSources = externalDataSources.length;
  const activeExternalSources = externalDataSources.filter(s => s.status === '正常').length;

  // 过滤数据源
  const filteredDataSources = externalDataSources.filter(source => {
    const matchesSearch = source.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         source.provider.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         source.description.toLowerCase().includes(searchTerm.toLowerCase());

    const matchesType = selectedType === 'all' || source.type === selectedType;
    const matchesStatus = selectedStatus === 'all' || source.status === selectedStatus;

    return matchesSearch && matchesType && matchesStatus;
  });

  const getStatusColor = (status: DataSourceStatus) => {
    switch (status) {
      case '正常':
        return 'bg-green-100 text-green-800 border-green-200 dark:bg-green-900/50 dark:text-green-300';
      case '异常':
        return 'bg-red-100 text-red-800 border-red-200 dark:bg-red-900/50 dark:text-red-300';
      case '离线':
        return 'bg-gray-100 text-gray-800 border-gray-200 dark:bg-gray-900/50 dark:text-gray-300';
      case '待配置':
        return 'bg-yellow-100 text-yellow-800 border-yellow-200 dark:bg-yellow-900/50 dark:text-yellow-300';
      default:
        return 'bg-gray-100 text-gray-800 border-gray-200 dark:bg-gray-900/50 dark:text-gray-300';
    }
  };

  const getStatusIcon = (status: DataSourceStatus) => {
    switch (status) {
      case '正常':
        return <CheckCircle className="w-4 h-4 text-green-600" />;
      case '异常':
        return <XCircle className="w-4 h-4 text-red-600" />;
      case '离线':
        return <WifiOff className="w-4 h-4 text-gray-500" />;
      case '待配置':
        return <AlertCircle className="w-4 h-4 text-yellow-600" />;
      default:
        return <AlertCircle className="w-4 h-4 text-gray-500" />;
    }
  };

  const getDataTypeIcon = (type: DataSourceType) => {
    switch (type) {
      case '气象数据':
        return <Cloud className="w-4 h-4 text-blue-600" />;
      case '卫星遥感':
        return <Satellite className="w-4 h-4 text-purple-600" />;
      case '土壤数据':
        return <Database className="w-4 h-4 text-green-600" />;
      case '作物生长':
        return <TrendingUp className="w-4 h-4 text-orange-600" />;
      default:
        return <Database className="w-4 h-4 text-gray-600" />;
    }
  };

  const getAccessMethodIcon = (method: string) => {
    switch (method) {
      case 'API对接':
        return <Link className="w-4 h-4" />;
      case 'FTP传输':
        return <Upload className="w-4 h-4" />;
      case 'WebSocket':
        return <Wifi className="w-4 h-4" />;
      case '手动上传':
        return <Upload className="w-4 h-4" />;
      default:
        return <Database className="w-4 h-4" />;
    }
  };

  const handleTestConnection = () => {
    toast.success('连接测试成功，数据接入正常');
  };

  const handleDataPreview = () => {
    setShowDataPreviewDialog(true);
  };

  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files;
    if (files && files.length > 0) {
      const fileArray = Array.from(files);
      setUploadedFiles(fileArray);
      setUploadedFile(fileArray[0]);
      let progress = 0;
      const interval = setInterval(() => {
        progress += 10;
        setUploadProgress(progress);
        if (progress >= 100) {
          clearInterval(interval);
          toast.success(`成功上传${fileArray.length}个文件`);
        }
      }, 200);
    }
  };

  return (
    <div className="p-6 space-y-6 bg-background">
      {/* 页面标题和说明 */}
      <div className="space-y-4">
        <div className="flex items-center gap-3">
          <Database className="w-8 h-8 text-blue-600" />
          <div>
            <h1 className="text-3xl font-bold text-foreground">多源数据接入</h1>
            <p className="text-muted-foreground">多源数据智能接入，构建全面精准的农业数据底座</p>
          </div>
        </div>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">外部数据源</p>
              <p className="mt-2 text-3xl text-sky-600">{activeExternalSources}/{totalExternalSources}</p>
              <p className="text-xs text-sky-600 mt-1">正常运行</p>
            </div>
            <Database className="w-12 h-12 text-sky-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">物联设备</p>
              <p className="mt-2 text-3xl text-green-600">3/5</p>
              <p className="text-xs text-green-600 mt-1">在线设备</p>
            </div>
            <Wifi className="w-12 h-12 text-green-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">数据质量</p>
              <p className="mt-2 text-3xl text-green-600">{dataQuality.accuracy}%</p>
              <p className="text-xs text-green-600 mt-1">准确率</p>
            </div>
            <CheckCircle2 className="w-12 h-12 text-green-600 opacity-50" />
          </div>
        </Card>

        <Card className="p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-xs text-muted-foreground">异常告警</p>
              <p className="mt-2 text-3xl text-amber-600">2</p>
              <p className="text-xs text-amber-600 mt-1">待处理</p>
            </div>
            <AlertTriangle className="w-12 h-12 text-amber-600 opacity-50" />
          </div>
        </Card>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-2">
          <TabsTrigger value="external">多源数据接入</TabsTrigger>
          <TabsTrigger value="iot">物联设备数据接入</TabsTrigger>
        </TabsList>

        {/* 多源数据接入 */}
        <TabsContent value="external" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-blue-50 to-indigo-50 border-blue-200 dark:from-blue-950/50 dark:to-indigo-950/50 dark:border-blue-800">
            <div className="flex items-start gap-2">
              <Database className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-blue-800 dark:text-blue-200">
                <p className="mb-2 font-medium">多源数据接入功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>灵活接入</strong>: 支持手动上传、API对接、FTP传输等多种方式</li>
                  <li>• <strong>数据校验</strong>: 提供格式适配与数据质量控制机制</li>
                  <li>• <strong>气象数据</strong>: 温度、湿度、光照、降水等实时气象信息</li>
                  <li>• <strong>卫星遥感</strong>: NDVI植被指数、作物长势监测影像</li>
                  <li>• <strong>高质量支撑</strong>: 确保数据完整性、准确性、时效性</li>
                </ul>
              </div>
            </div>
          </Card>

          <div className="flex gap-4">
            <Button onClick={() => {
              setSelectedDataSource(null);
              setSelectedAccessMethod('API对接');
              setUploadedFile(null);
              setUploadedFiles([]);
              setUploadProgress(0);
              setShowDataSourceDialog(true);
            }}>
              <Plus className="w-4 h-4 mr-2" />
              添加数据源
            </Button>
            <Button variant="outline" onClick={() => setShowUploadDialog(true)}>
              <Upload className="w-4 h-4 mr-2" />
              手动上传数据
            </Button>
            <Button variant="outline" onClick={() => setShowValidationDialog(true)}>
              <CheckCircle2 className="w-4 h-4 mr-2" />
              数据校验规则
            </Button>
          </div>

          {/* 筛选条件 */}
          <Card className="p-4">
            <div className="flex items-center gap-4">
              <div className="flex items-center gap-2">
                <Search className="w-4 h-4 text-muted-foreground" />
                <Input
                  placeholder="搜索数据源..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="w-64"
                />
              </div>

              <Select value={selectedType} onValueChange={setSelectedType}>
                <SelectTrigger className="w-40">
                  <SelectValue placeholder="数据类型" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部类型</SelectItem>
                  <SelectItem value="气象数据">气象数据</SelectItem>
                  <SelectItem value="卫星遥感">卫星遥感</SelectItem>
                  <SelectItem value="土壤数据">土壤数据</SelectItem>
                  <SelectItem value="作物生长">作物生长</SelectItem>
                  <SelectItem value="其他">其他</SelectItem>
                </SelectContent>
              </Select>

              <Select value={selectedStatus} onValueChange={setSelectedStatus}>
                <SelectTrigger className="w-32">
                  <SelectValue placeholder="状态" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部状态</SelectItem>
                  <SelectItem value="正常">正常</SelectItem>
                  <SelectItem value="异常">异常</SelectItem>
                  <SelectItem value="离线">离线</SelectItem>
                  <SelectItem value="待配置">待配置</SelectItem>
                </SelectContent>
              </Select>

              <Button variant="outline" size="sm">
                <RefreshCw className="w-4 h-4 mr-2" />
                刷新
              </Button>
            </div>
          </Card>

          {/* 数据源列表 */}
          <Card className="bg-card border-border">
            <div className="p-4 border-b border-border bg-muted/30">
              <h3 className="flex items-center gap-2 text-lg font-semibold">
                <Database className="w-5 h-5 text-blue-600" />
                外部数据源
              </h3>
            </div>

            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow className="bg-muted/50">
                    <TableHead className="font-medium">数据源名称</TableHead>
                    <TableHead className="font-medium">数据类型</TableHead>
                    <TableHead className="font-medium">提供商</TableHead>
                    <TableHead className="font-medium">接入方式</TableHead>
                    <TableHead className="font-medium">更新频率</TableHead>
                    <TableHead className="font-medium">数据点数</TableHead>
                    <TableHead className="font-medium">最后更新</TableHead>
                    <TableHead className="font-medium">状态</TableHead>
                    <TableHead className="font-medium">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredDataSources.map((source) => (
                    <TableRow key={source.id} className="hover:bg-muted/30">
                      <TableCell>
                        <div className="flex items-center gap-2">
                          {getDataTypeIcon(source.type)}
                          <span className="font-medium">{source.name}</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline" className="font-light">{source.type}</Badge>
                      </TableCell>
                      <TableCell className="text-xs">{source.provider}</TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          {getAccessMethodIcon(source.accessMethod)}
                          <Badge variant="outline" className="font-light">{source.accessMethod}</Badge>
                        </div>
                      </TableCell>
                      <TableCell className="text-xs">{source.updateFrequency}</TableCell>
                      <TableCell className="text-xs">{source.dataPoints.toLocaleString()}</TableCell>
                      <TableCell className="text-xs">{source.lastUpdateTime}</TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          {getStatusIcon(source.status)}
                          <Badge className={`font-light ${getStatusColor(source.status)}`}>{source.status}</Badge>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex gap-2">
                          {source.accessMethod !== '手动上传' && (
                            <Button size="sm" variant="outline" onClick={handleTestConnection}>
                              <Link className="w-3 h-3" />
                            </Button>
                          )}
                          <Button size="sm" variant="outline" onClick={() => {
                            setSelectedDataSource(source);
                            setSelectedAccessMethod(source.accessMethod);
                            setShowDataSourceDialog(true);
                          }}>
                            <Edit className="w-3 h-3" />
                          </Button>
                          <Button size="sm" variant="outline" onClick={handleDataPreview}>
                            <Eye className="w-3 h-3" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </Card>
        </TabsContent>
      </Tabs>

      {/* 数据源配置对话框 */}
      <Dialog open={showDataSourceDialog} onOpenChange={setShowDataSourceDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Database className="w-5 h-5" />
              {selectedDataSource ? '编辑数据源' : '添加数据源'}
            </DialogTitle>
            <DialogDescription>
              配置外部数据源的接入方式和参数
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>数据源名称</Label>
                <Input placeholder="输入数据源名称" defaultValue={selectedDataSource?.name} />
              </div>
              <div>
                <Label>数据类型</Label>
                <Select defaultValue={selectedDataSource?.type}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择数据类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="气象数据">气象数据</SelectItem>
                    <SelectItem value="卫星遥感">卫星遥感</SelectItem>
                    <SelectItem value="土壤数据">土壤数据</SelectItem>
                    <SelectItem value="作物生长">作物生长</SelectItem>
                    <SelectItem value="其他">其他</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>提供商</Label>
                <Input placeholder="输入数据提供商" defaultValue={selectedDataSource?.provider} />
              </div>
              <div>
                <Label>接入方式</Label>
                <Select value={selectedAccessMethod} onValueChange={(value: AccessMethod) => setSelectedAccessMethod(value)}>
                  <SelectTrigger>
                    <SelectValue placeholder="选择接入方式" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="API对接">API对接</SelectItem>
                    <SelectItem value="FTP传输">FTP传输</SelectItem>
                    <SelectItem value="WebSocket">WebSocket</SelectItem>
                    <SelectItem value="手动上传">手动上传</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {selectedAccessMethod !== '手动上传' && (
              <div>
                <Label>API端点/服务器地址</Label>
                <Input placeholder="输入API端点或服务器地址" defaultValue={selectedDataSource?.apiEndpoint} />
              </div>
            )}

            <div>
              <Label>更新频率</Label>
              <Select defaultValue={selectedDataSource?.updateFrequency}>
                <SelectTrigger>
                  <SelectValue placeholder="选择更新频率" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="实时">实时</SelectItem>
                  <SelectItem value="每5分钟">每5分钟</SelectItem>
                  <SelectItem value="每30分钟">每30分钟</SelectItem>
                  <SelectItem value="每小时">每小时</SelectItem>
                  <SelectItem value="每天">每天</SelectItem>
                  <SelectItem value="每周">每周</SelectItem>
                  <SelectItem value="每月">每月</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <div>
              <Label>数据描述</Label>
              <Textarea
                placeholder="输入数据源的详细描述"
                className="resize-none"
                rows={3}
                defaultValue={selectedDataSource?.description}
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDataSourceDialog(false)}>
              取消
            </Button>
            <Button onClick={() => {
              toast.success(selectedDataSource ? '数据源更新成功' : '数据源添加成功');
              setShowDataSourceDialog(false);
            }}>
              保存配置
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 手动上传数据对话框 */}
      <Dialog open={showUploadDialog} onOpenChange={setShowUploadDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Upload className="w-5 h-5 text-blue-600" />
              手动上传数据
            </DialogTitle>
            <DialogDescription>
              支持CSV、JSON、XML等多种格式数据上传，支持多文件同时上传
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div>
              <Label>选择文件</Label>
              <Input
                type="file"
                multiple
                accept=".csv,.json,.xml,.xlsx"
                onChange={handleFileUpload}
              />
            </div>

            {uploadProgress > 0 && (
              <div>
                <div className="flex items-center justify-between mb-2">
                  <span className="text-sm">上传进度</span>
                  <span className="text-sm font-medium">{uploadProgress}%</span>
                </div>
                <Progress value={uploadProgress} className="h-2" />
              </div>
            )}

            <Card className="p-4 bg-blue-50 dark:bg-blue-950/30 border-blue-200 dark:border-blue-800">
              <h4 className="text-sm mb-3 flex items-center gap-2">
                <CheckCircle2 className="w-4 h-4 text-blue-600" />
                数据质量校验
              </h4>
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <span className="text-xs">自动检测数据完整性</span>
                  <Switch defaultChecked />
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-xs">验证数据格式规范</span>
                  <Switch defaultChecked />
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-xs">异常值自动标记</span>
                  <Switch defaultChecked />
                </div>
              </div>
            </Card>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowUploadDialog(false)}>
              取消
            </Button>
            <Button onClick={() => {
              toast.success('数据上传成功');
              setShowUploadDialog(false);
            }}>
              开始上传
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 数据校验规则对话框 */}
      <Dialog open={showValidationDialog} onOpenChange={setShowValidationDialog}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <CheckCircle2 className="w-5 h-5" />
              数据校验规则
            </DialogTitle>
            <DialogDescription>
              配置数据质量校验规则和异常处理策略
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <Label className="text-sm">数据完整性检查</Label>
                <Switch defaultChecked />
              </div>
              <div className="flex items-center justify-between">
                <Label className="text-sm">数据格式验证</Label>
                <Switch defaultChecked />
              </div>
              <div className="flex items-center justify-between">
                <Label className="text-sm">数值范围校验</Label>
                <Switch defaultChecked />
              </div>
              <div className="flex items-center justify-between">
                <Label className="text-sm">时间戳连续性</Label>
                <Switch defaultChecked />
              </div>
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowValidationDialog(false)}>
              取消
            </Button>
            <Button onClick={() => {
              toast.success('校验规则保存成功');
              setShowValidationDialog(false);
            }}>
              保存规则
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 数据预览对话框 */}
      <Dialog open={showDataPreviewDialog} onOpenChange={setShowDataPreviewDialog}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Eye className="w-5 h-5" />
              数据预览
            </DialogTitle>
            <DialogDescription>
              查看数据源的详细信息和样本数据
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            {selectedDataSource && (
              <>
                <Card className="p-4">
                  <h4 className="font-medium mb-3">{selectedDataSource.name}</h4>
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div>
                      <span className="text-muted-foreground">数据类型：</span>
                      <span className="ml-2">{selectedDataSource.type}</span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">提供商：</span>
                      <span className="ml-2">{selectedDataSource.provider}</span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">接入方式：</span>
                      <span className="ml-2">{selectedDataSource.accessMethod}</span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">更新频率：</span>
                      <span className="ml-2">{selectedDataSource.updateFrequency}</span>
                    </div>
                  </div>
                  <div className="mt-3">
                    <span className="text-muted-foreground">描述：</span>
                    <p className="mt-1 text-sm">{selectedDataSource.description}</p>
                  </div>
                </Card>

                <Card className="p-4">
                  <h4 className="font-medium mb-3">数据字段</h4>
                  <div className="flex flex-wrap gap-2">
                    {selectedDataSource.dataFields.map((field, index) => (
                      <Badge key={index} variant="outline">{field}</Badge>
                    ))}
                  </div>
                </Card>

                <Card className="p-4">
                  <h4 className="font-medium mb-3">统计信息</h4>
                  <div className="grid grid-cols-3 gap-4 text-sm">
                    <div>
                      <span className="text-muted-foreground">数据点总数：</span>
                      <span className="ml-2 font-medium">{selectedDataSource.dataPoints.toLocaleString()}</span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">最后更新：</span>
                      <span className="ml-2">{selectedDataSource.lastUpdateTime}</span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">当前状态：</span>
                      <Badge className={`ml-2 ${getStatusColor(selectedDataSource.status)}`}>
                        {selectedDataSource.status}
                      </Badge>
                    </div>
                  </div>
                </Card>
              </>
            )}
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDataPreviewDialog(false)}>
              关闭
            </Button>
            <Button>
              <Download className="w-4 h-4 mr-2" />
              导出数据
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}