import { useState, useEffect } from 'react';
import { AIDecisionDashboard } from '../ai/AIDecisionDashboard';
import { AIDecisionDetail } from '../ai/AIDecisionDetail';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Input } from '../ui/input';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '../ui/dialog';
import { Label } from '../ui/label';
import { Progress } from '../ui/progress';
import {
  LayoutDashboard,
  MapPin,
  Search,
  Download,
  RefreshCw,
  CheckCircle,
  AlertCircle,
  Eye,
  Filter,
  TrendingUp,
  Calendar,
  Droplets,
  Bug,
  Sprout,
  AlertTriangle,
  ThermometerSun,
  CloudRain,
  Leaf,
  BarChart3,
  PieChart as PieChartIcon,
  Activity,
  FileText,
  Database,
  Brain,
  Layers,
  Target,
  Zap,
  Clock,
  MapPinned,
  Navigation2,
  Maximize2,
  ChevronRight,
  Info,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as RechartsTooltip,
  Legend,
  ResponsiveContainer,
  AreaChart,
  Area,
  PieChart,
  Pie,
  Cell,
  RadarChart,
  PolarGrid,
  PolarAngleAxis,
  PolarRadiusAxis,
  Radar,
} from 'recharts';

interface AIDecisionSupportProps {
  activePath?: string;
}

type DecisionType = '灌溉决策' | '病虫害预警' | '施肥决策' | '气象预警' | '生长监测';
type DecisionLevel = '紧急' | '重要' | '一般' | '建议';
type DecisionStatus = '待执行' | '执行中' | '已完成' | '已忽略';

interface FieldDecision {
  id: string;
  fieldId: string;
  fieldName: string;
  location: { lat: number; lng: number };
  cropType: string;
  area: number;
  decisionType: DecisionType;
  decisionLevel: DecisionLevel;
  status: DecisionStatus;
  content: string;
  generatedTime: string;
  deadline?: string;
  confidence: number;
}

interface DecisionDetail {
  id: string;
  decisionNo: string;
  fieldInfo: {
    fieldId: string;
    fieldName: string;
    area: number;
    cropType: string;
    growthStage: string;
    soilType: string;
  };
  decisionType: DecisionType;
  decisionLevel: DecisionLevel;
  generatedTime: string;
  deadline?: string;
  dataSnapshot: {
    source: string;
    timestamp: string;
    values: Record<string, any>;
  }[];
  modelAnalysis: {
    modelName: string;
    modelVersion: string;
    rawOutput: any;
    confidence: number;
    processingTime: number;
  };
  ruleLogic: {
    ruleId: string;
    ruleName: string;
    ruleType: string;
    condition: string;
    matched: boolean;
    calculation?: string;
    result?: string;
  }[];
  finalDecision: string;
  reasoning: string;
  confidence: number;
  status: DecisionStatus;
}

export function AIDecisionSupport({ activePath }: AIDecisionSupportProps) {
  // 如果是决策看板路径，直接返回决策看板组件
  if (activePath && activePath.includes('/support/dashboard')) {
    return <AIDecisionDashboard activePath={activePath} />;
  }

  // 如果是决策详情路径，直接返回决策详情组件
  if (activePath && activePath.includes('/support/detail')) {
    return <AIDecisionDetail activePath={activePath} />;
  }

  const [activeTab, setActiveTab] = useState('map');
  const [selectedDecision, setSelectedDecision] = useState<DecisionDetail | null>(null);
  const [selectedField, setSelectedField] = useState<string | null>(null);

  // 根据路径自动切换Tab
  useEffect(() => {
    if (activePath) {
      // 可以在这里根据其他路径切换Tab
    }
  }, [activePath]);

  // 地块决策数据
  const [fieldDecisions] = useState<FieldDecision[]>([
    {
      id: 'fd-1',
      fieldId: 'field-001',
      fieldName: '1号大棚',
      location: { lat: 31.23, lng: 121.47 },
      cropType: '番茄',
      area: 2.5,
      decisionType: '病虫害预警',
      decisionLevel: '紧急',
      status: '待执行',
      content: '检测到早疫病中度感染，建议立即使用百菌清喷施',
      generatedTime: '2024-10-15 14:32:18',
      deadline: '2024-10-18 14:32:18',
      confidence: 0.94,
    },
    {
      id: 'fd-2',
      fieldId: 'field-002',
      fieldName: '2号田块',
      location: { lat: 31.24, lng: 121.48 },
      cropType: '黄瓜',
      area: 3.2,
      decisionType: '施肥决策',
      decisionLevel: '一般',
      status: '待执行',
      content: '建议施用复合肥（N-P-K 15-10-5）25kg/亩',
      generatedTime: '2024-10-14 08:15:42',
      deadline: '2024-10-17 08:15:42',
      confidence: 0.89,
    },
    {
      id: 'fd-3',
      fieldId: 'field-003',
      fieldName: '3号田块',
      location: { lat: 31.25, lng: 121.49 },
      cropType: '番茄',
      area: 5.0,
      decisionType: '灌溉决策',
      decisionLevel: '重要',
      status: '执行中',
      content: '建议灌溉550升，最佳时段06:00-08:00',
      generatedTime: '2024-10-15 18:05:32',
      confidence: 0.92,
    },
    {
      id: 'fd-4',
      fieldId: 'field-004',
      fieldName: '4号田块',
      location: { lat: 31.22, lng: 121.46 },
      cropType: '辣椒',
      area: 2.8,
      decisionType: '气象预警',
      decisionLevel: '重要',
      status: '待执行',
      content: '未来48小时有强降雨，建议加固设施并检查排水系统',
      generatedTime: '2024-10-15 09:20:15',
      deadline: '2024-10-16 09:20:15',
      confidence: 0.88,
    },
    {
      id: 'fd-5',
      fieldId: 'field-005',
      fieldName: '5号大棚',
      location: { lat: 31.26, lng: 121.50 },
      cropType: '黄瓜',
      area: 1.8,
      decisionType: '生长监测',
      decisionLevel: '建议',
      status: '已完成',
      content: '生长速度正常，建议保持当前管理措施',
      generatedTime: '2024-10-15 12:30:00',
      confidence: 0.85,
    },
  ]);

  // 决策详情数据
  const decisionDetails: DecisionDetail = {
    id: 'dd-1',
    decisionNo: 'DEC-20241015-001',
    fieldInfo: {
      fieldId: 'field-001',
      fieldName: '1号大棚',
      area: 2.5,
      cropType: '番茄',
      growthStage: '结果期',
      soilType: '沙壤土',
    },
    decisionType: '病虫害预警',
    decisionLevel: '紧急',
    generatedTime: '2024-10-15 14:32:18',
    deadline: '2024-10-18 14:32:18',
    dataSnapshot: [
      {
        source: '监控摄像头-CAM001',
        timestamp: '2024-10-15 14:30:00',
        values: {
          图像分析: '叶片黄化病斑',
          病斑数量: 15,
          叶片受损率: '23%',
        },
      },
      {
        source: '环境传感器-ENV001',
        timestamp: '2024-10-15 14:30:00',
        values: {
          温度: 26.8,
          湿度: 72,
          光照强度: 15000,
        },
      },
      {
        source: '历史病害数据库',
        timestamp: '2024-10-15 14:30:00',
        values: {
          历史记录: '去年同期发生过早疫病',
          发病频率: '中等',
          防治效果: '良好',
        },
      },
    ],
    modelAnalysis: {
      modelName: '病虫害识别模型',
      modelVersion: 'v1.8.0',
      rawOutput: {
        病害类型: '番茄早疫病',
        置信度: 0.94,
        感染程度: '中度',
        推荐措施: ['隔离病株', '使用百菌清', '加强通风'],
      },
      confidence: 0.94,
      processingTime: 1.8,
    },
    ruleLogic: [
      {
        ruleId: 'rule-002',
        ruleName: '病虫害预警等级判定',
        ruleType: '加权规则',
        condition: '模型置信度 × 0.4 + 历史频率 × 0.3 + 环境适宜度 × 0.3',
        matched: true,
        calculation: '0.94 × 0.4 + 0.6 × 0.3 + 0.8 × 0.3 = 0.86',
        result: '总分 0.86 > 0.8，判定为紧急级别',
      },
      {
        ruleId: 'rule-005',
        ruleName: '高温高湿病害风险',
        ruleType: '阈值规则',
        condition: '温度 > 25℃ AND 湿度 > 70%',
        matched: true,
        result: '��境条件适宜病菌繁殖，提升预警等级',
      },
    ],
    finalDecision: '紧急预警！1号大棚番茄疑似早疫病中度感染，建议立即隔离病株，72小时内使用百菌清喷施防治，加强棚内通风降低湿度',
    reasoning: '根据监控摄像头图像分析，检测到叶片黄化病斑，病斑数量15个，叶片受损率23%。病虫害识别模型以94%的置信度判定为番茄早疫病中度感染。当前环境温度26.8℃、湿度72%，高温高湿条件极适合病菌繁殖。结合历史病害记录（去年同期发生过早疫病）和环境因素，加权评分0.86属于紧急级别。需立即采取防控措施避免扩散，建议72小时内完成处理。',
    confidence: 0.94,
    status: '待执行',
  };

  // 统计数据
  const totalDecisions = fieldDecisions.length;
  const urgentDecisions = fieldDecisions.filter(d => d.decisionLevel === '紧急').length;
  const pendingDecisions = fieldDecisions.filter(d => d.status === '待执行').length;
  const avgConfidence = fieldDecisions.reduce((sum, d) => sum + d.confidence, 0) / totalDecisions;

  // 决策类型分布
  const decisionTypeDistribution = [
    { name: '灌溉决策', value: 8, color: '#3b82f6' },
    { name: '病虫害预警', value: 5, color: '#f59e0b' },
    { name: '施肥决策', value: 6, color: '#10b981' },
    { name: '气象预警', value: 3, color: '#8b5cf6' },
    { name: '生长监测', value: 4, color: '#ec4899' },
  ];

  // 决策趋势数据
  const decisionTrend = [
    { date: '10-11', 灌溉: 8, 病虫害: 3, 施肥: 4, 气象: 1 },
    { date: '10-12', 灌溉: 10, 病虫害: 5, 施肥: 5, 气象: 2 },
    { date: '10-13', 灌溉: 7, 病虫害: 4, 施肥: 3, 气象: 1 },
    { date: '10-14', 灌溉: 9, 病虫害: 6, 施肥: 6, 气象: 2 },
    { date: '10-15', 灌溉: 11, 病虫害: 7, 施肥: 5, 气象: 3 },
  ];

  // 决策执行率
  const executionRate = [
    { type: '待执行', count: 12, percentage: 46 },
    { type: '执行中', count: 8, percentage: 31 },
    { type: '已完成', count: 5, percentage: 19 },
    { type: '已忽略', count: 1, percentage: 4 },
  ];

  const COLORS = ['#3b82f6', '#f59e0b', '#10b981', '#8b5cf6', '#ec4899'];

  const getLevelColor = (level: DecisionLevel) => {
    switch (level) {
      case '紧急': return 'bg-error-muted text-error-muted-foreground border-error';
      case '重要': return 'bg-warning-muted text-warning-muted-foreground border-warning';
      case '一般': return 'bg-info-muted text-info-muted-foreground border-info';
      case '建议': return 'bg-muted text-muted-foreground border-border';
      default: return 'bg-muted text-muted-foreground border-border';
    }
  };

  const getStatusColor = (status: DecisionStatus) => {
    switch (status) {
      case '待执行': return 'bg-warning-muted text-warning-muted-foreground';
      case '执行中': return 'bg-info-muted text-info-muted-foreground';
      case '已完成': return 'bg-success-muted text-success-muted-foreground';
      case '已忽略': return 'bg-muted text-muted-foreground';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  const getDecisionIcon = (type: DecisionType) => {
    switch (type) {
      case '灌溉决策': return <Droplets className="w-4 h-4" />;
      case '病虫害预警': return <Bug className="w-4 h-4" />;
      case '施肥决策': return <Sprout className="w-4 h-4" />;
      case '气象预警': return <CloudRain className="w-4 h-4" />;
      case '生长监测': return <Leaf className="w-4 h-4" />;
      default: return <Activity className="w-4 h-4" />;
    }
  };

  const handleViewDetail = (decision: FieldDecision) => {
    setSelectedDecision(decisionDetails);
    toast.success('已加载决策详情');
  };

  const handleExecuteDecision = (decisionId: string) => {
    toast.success('决策已标记为执行中');
  };

  const handleIgnoreDecision = (decisionId: string) => {
    toast.success('决策已忽略');
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2>智能决策支持</h2>
          <p className="text-sm text-muted-foreground mt-1">
            全局决策动态一目了然，助力精准农业管理
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline">
            <RefreshCw className="w-4 h-4 mr-2" />
            刷新数据
          </Button>
          <Button variant="outline">
            <Download className="w-4 h-4 mr-2" />
            导出报告
          </Button>
        </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-info">{totalDecisions}</p>
              <p className="text-xs text-info mt-1">全部地块</p>
            </div>
            <LayoutDashboard className="w-12 h-12 text-info 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-error">{urgentDecisions}</p>
              <p className="text-xs text-error mt-1">需立即处理</p>
            </div>
            <AlertCircle className="w-12 h-12 text-error 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-warning">{pendingDecisions}</p>
              <p className="text-xs text-warning mt-1">等待处理</p>
            </div>
            <Clock className="w-12 h-12 text-warning 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-success">{(avgConfidence * 100).toFixed(1)}%</p>
              <p className="text-xs text-success mt-1">决策准确性</p>
            </div>
            <Target className="w-12 h-12 text-success opacity-50" />
          </div>
        </Card>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-2">
          <TabsTrigger value="dashboard">决策看板</TabsTrigger>
          <TabsTrigger value="detail">决策详情</TabsTrigger>
        </TabsList>

        {/* 决策看板 */}
        <TabsContent value="dashboard" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-blue-50 to-cyan-50 border-blue-200">
            <div className="flex items-start gap-2">
              <LayoutDashboard className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-blue-900">
                <p className="mb-2">决策看板功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>地图可视化</strong>: 地块分布与决策状态一目了然</li>
                  <li>• <strong>卡片列表</strong>: 决策摘要信息快速浏览</li>
                  <li>• <strong>图表分析</strong>: 决策趋势、类别统计可视化</li>
                  <li>• <strong>多维筛选</strong>: 按时间、地块、作物类型等筛选钻取</li>
                  <li>• <strong>全局视角</strong>: 快速掌握全局决策动态</li>
                </ul>
              </div>
            </div>
          </Card>

          {/* 筛选器 */}
          <Card className="p-4">
            <div className="flex gap-4">
              <div className="flex-1">
                <Input placeholder="搜索地块名称、作物类型..." prefix={<Search className="w-4 h-4" />} />
              </div>
              <Select defaultValue="all-type">
                <SelectTrigger className="w-40">
                  <SelectValue placeholder="决策类型" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all-type">全部类型</SelectItem>
                  <SelectItem value="irrigation">灌溉决策</SelectItem>
                  <SelectItem value="pest">病虫害预警</SelectItem>
                  <SelectItem value="fertilizer">施肥决策</SelectItem>
                  <SelectItem value="weather">气象预警</SelectItem>
                </SelectContent>
              </Select>
              <Select defaultValue="all-level">
                <SelectTrigger className="w-40">
                  <SelectValue placeholder="决策等级" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all-level">全部等级</SelectItem>
                  <SelectItem value="urgent">紧急</SelectItem>
                  <SelectItem value="important">重要</SelectItem>
                  <SelectItem value="normal">一般</SelectItem>
                </SelectContent>
              </Select>
              <Select defaultValue="all-status">
                <SelectTrigger className="w-40">
                  <SelectValue placeholder="执行状态" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all-status">全部状态</SelectItem>
                  <SelectItem value="pending">待执行</SelectItem>
                  <SelectItem value="executing">执行中</SelectItem>
                  <SelectItem value="completed">已完成</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </Card>

          {/* 地图可视化 */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-4">
              <h4 className="flex items-center gap-2">
                <MapPinned className="w-5 h-5 text-blue-600" />
                地块决策分布地图
              </h4>
              <Button size="sm" variant="outline">
                <Maximize2 className="w-3 h-3 mr-1" />
                全屏查看
              </Button>
            </div>
            
            {/* 模拟地图界面 */}
            <div className="relative bg-gradient-to-br from-blue-50 to-green-50 rounded-lg border-2 border-dashed border-blue-300 h-96 overflow-hidden">
              <div className="absolute inset-0 flex items-center justify-center">
                <div className="text-center">
                  <MapPin className="w-16 h-16 text-blue-400 mx-auto mb-2" />
                  <p className="text-sm text-muted-foreground">地图可视化区域</p>
                  <p className="text-xs text-muted-foreground mt-1">显示各地块位置、决策类型和等级</p>
                </div>
              </div>
              
              {/* 模拟地块标记 */}
              <div className="absolute top-20 left-32 group cursor-pointer" onClick={() => setSelectedField('field-001')}>
                <div className="relative">
                  <div className="w-4 h-4 bg-red-500 rounded-full animate-pulse"></div>
                  <div className="absolute -top-8 left-1/2 -translate-x-1/2 bg-white px-2 py-1 rounded shadow-lg whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity">
                    <p className="text-xs">1号大棚 - 紧急</p>
                  </div>
                </div>
              </div>
              
              <div className="absolute top-40 left-56 group cursor-pointer" onClick={() => setSelectedField('field-002')}>
                <div className="relative">
                  <div className="w-4 h-4 bg-blue-500 rounded-full animate-pulse"></div>
                  <div className="absolute -top-8 left-1/2 -translate-x-1/2 bg-white px-2 py-1 rounded shadow-lg whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity">
                    <p className="text-xs">2号田块 - 一般</p>
                  </div>
                </div>
              </div>
              
              <div className="absolute top-28 right-40 group cursor-pointer" onClick={() => setSelectedField('field-003')}>
                <div className="relative">
                  <div className="w-4 h-4 bg-orange-500 rounded-full animate-pulse"></div>
                  <div className="absolute -top-8 left-1/2 -translate-x-1/2 bg-white px-2 py-1 rounded shadow-lg whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity">
                    <p className="text-xs">3号田块 - 重要</p>
                  </div>
                </div>
              </div>

              {/* 图例 */}
              <div className="absolute bottom-4 left-4 bg-white p-3 rounded-lg shadow-lg">
                <p className="text-xs mb-2">决策等级</p>
                <div className="space-y-1">
                  <div className="flex items-center gap-2 text-xs">
                    <div className="w-3 h-3 bg-red-500 rounded-full"></div>
                    <span>紧急</span>
                  </div>
                  <div className="flex items-center gap-2 text-xs">
                    <div className="w-3 h-3 bg-orange-500 rounded-full"></div>
                    <span>重要</span>
                  </div>
                  <div className="flex items-center gap-2 text-xs">
                    <div className="w-3 h-3 bg-blue-500 rounded-full"></div>
                    <span>一般</span>
                  </div>
                  <div className="flex items-center gap-2 text-xs">
                    <div className="w-3 h-3 bg-muted-foreground rounded-full"></div>
                    <span>建议</span>
                  </div>
                </div>
              </div>
            </div>
          </Card>

          {/* 决策卡片列表 */}
          <Card className="p-6">
            <h4 className="mb-4 flex items-center gap-2">
              <FileText className="w-5 h-5 text-green-600" />
              决策列表
            </h4>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {fieldDecisions.map((decision) => (
                <Card key={decision.id} className={`p-4 border-l-4 ${
                  decision.decisionLevel === '紧急' ? 'border-l-red-500 bg-red-50/50' :
                  decision.decisionLevel === '重要' ? 'border-l-orange-500 bg-orange-50/50' :
                  decision.decisionLevel === '一般' ? 'border-l-blue-500 bg-blue-50/50' :
                  'border-l-gray-500 bg-muted'
                }`}>
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-center gap-2">
                      <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${
                        decision.decisionType === '灌溉决策' ? 'bg-blue-100 text-blue-600' :
                        decision.decisionType === '病虫害预警' ? 'bg-orange-100 text-orange-600' :
                        decision.decisionType === '施肥决策' ? 'bg-green-100 text-green-600' :
                        decision.decisionType === '气象预警' ? 'bg-purple-100 text-purple-600' :
                        'bg-pink-100 text-pink-600'
                      }`}>
                        {getDecisionIcon(decision.decisionType)}
                      </div>
                      <div>
                        <h5>{decision.fieldName}</h5>
                        <p className="text-xs text-muted-foreground">{decision.cropType} · {decision.area}亩</p>
                      </div>
                    </div>
                    <Badge className={getLevelColor(decision.decisionLevel)}>
                      {decision.decisionLevel}
                    </Badge>
                  </div>

                  <div className="mb-3">
                    <div className="flex items-center gap-2 mb-2">
                      <Badge variant="outline">{decision.decisionType}</Badge>
                      <Badge className={getStatusColor(decision.status)}>{decision.status}</Badge>
                    </div>
                    <p className="text-sm">{decision.content}</p>
                  </div>

                  <div className="flex items-center justify-between text-xs text-muted-foreground mb-3">
                    <div className="flex items-center gap-1">
                      <Clock className="w-3 h-3" />
                      {decision.generatedTime}
                    </div>
                    {decision.deadline && (
                      <div className="flex items-center gap-1 text-orange-600">
                        <AlertCircle className="w-3 h-3" />
                        截止: {decision.deadline.substring(5)}
                      </div>
                    )}
                  </div>

                  <div className="mb-3">
                    <div className="flex items-center justify-between text-xs mb-1">
                      <span className="text-muted-foreground">置信度</span>
                      <span className="font-medium">{(decision.confidence * 100).toFixed(1)}%</span>
                    </div>
                    <Progress value={decision.confidence * 100} />
                  </div>

                  <div className="flex gap-2">
                    <Button size="sm" className="flex-1" onClick={() => handleViewDetail(decision)}>
                      <Eye className="w-3 h-3 mr-1" />
                      查看详情
                    </Button>
                    {decision.status === '待执行' && (
                      <Button size="sm" variant="outline" onClick={() => handleExecuteDecision(decision.id)}>
                        <Zap className="w-3 h-3 mr-1" />
                        执行
                      </Button>
                    )}
                  </div>
                </Card>
              ))}
            </div>
          </Card>

          {/* 图表分析 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <TrendingUp className="w-4 h-4 text-blue-600" />
                决策生成趋势
              </h4>
              <ResponsiveContainer width="100%" height={250}>
                <AreaChart data={decisionTrend}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="date" />
                  <YAxis />
                  <RechartsTooltip />
                  <Legend />
                  <Area type="monotone" dataKey="灌溉" stackId="1" stroke="#3b82f6" fill="#3b82f6" fillOpacity={0.6} />
                  <Area type="monotone" dataKey="病虫害" stackId="1" stroke="#f59e0b" fill="#f59e0b" fillOpacity={0.6} />
                  <Area type="monotone" dataKey="施肥" stackId="1" stroke="#10b981" fill="#10b981" fillOpacity={0.6} />
                  <Area type="monotone" dataKey="气象" stackId="1" stroke="#8b5cf6" fill="#8b5cf6" fillOpacity={0.6} />
                </AreaChart>
              </ResponsiveContainer>
            </Card>

            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <PieChartIcon className="w-4 h-4 text-green-600" />
                决策类型分布
              </h4>
              <ResponsiveContainer width="100%" height={250}>
                <PieChart>
                  <Pie
                    data={decisionTypeDistribution}
                    cx="50%"
                    cy="50%"
                    labelLine={false}
                    label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`}
                    outerRadius={80}
                    fill="#8884d8"
                    dataKey="value"
                  >
                    {decisionTypeDistribution.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.color} />
                    ))}
                  </Pie>
                  <RechartsTooltip />
                </PieChart>
              </ResponsiveContainer>
            </Card>

            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <BarChart3 className="w-4 h-4 text-purple-600" />
                决策��行率
              </h4>
              <ResponsiveContainer width="100%" height={250}>
                <BarChart data={executionRate} layout="vertical">
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis type="number" />
                  <YAxis dataKey="type" type="category" />
                  <RechartsTooltip />
                  <Bar dataKey="count" fill="#8b5cf6">
                    {executionRate.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                    ))}
                  </Bar>
                </BarChart>
              </ResponsiveContainer>
            </Card>

            <Card className="p-4">
              <h4 className="mb-4 flex items-center gap-2">
                <Activity className="w-4 h-4 text-orange-600" />
                作物决策热度
              </h4>
              <ResponsiveContainer width="100%" height={250}>
                <RadarChart data={[
                  { crop: '番茄', 决策数量: 8, 紧急度: 7 },
                  { crop: '黄瓜', 决策数量: 6, 紧急度: 5 },
                  { crop: '辣椒', 决策数量: 5, 紧急度: 4 },
                  { crop: '茄子', 决策数量: 4, 紧急度: 3 },
                  { crop: '青菜', 决策数量: 3, 紧急度: 2 },
                ]}>
                  <PolarGrid />
                  <PolarAngleAxis dataKey="crop" />
                  <PolarRadiusAxis />
                  <Radar name="决策数量" dataKey="决策数量" stroke="#3b82f6" fill="#3b82f6" fillOpacity={0.6} />
                  <Radar name="紧急度" dataKey="紧急度" stroke="#f59e0b" fill="#f59e0b" fillOpacity={0.6} />
                  <Legend />
                </RadarChart>
              </ResponsiveContainer>
            </Card>
          </div>
        </TabsContent>

        {/* 决策详情 */}
        <TabsContent value="detail" className="space-y-4">
          <Card className="p-4 bg-gradient-to-r from-purple-50 to-pink-50 border-purple-200">
            <div className="flex items-start gap-2">
              <Eye className="w-5 h-5 text-purple-600 flex-shrink-0 mt-0.5" />
              <div className="text-sm text-purple-900">
                <p className="mb-2">决策详情功能：</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>数据快照</strong>: 完整记录输入数据值及来源</li>
                  <li>• <strong>模型分析</strong>: 展示模型原始输出与置信度</li>
                  <li>• <strong>规则逻辑</strong>: 匹配的规则内容与计算过程</li>
                  <li>• <strong>推理过程</strong>: 清晰展示决策生成依据</li>
                  <li>• <strong>增强信任</strong>: 提升用户对决策结果的理解</li>
                  <li>• <strong>经验沉淀</strong>: 支持决策复核与知识积累</li>
                </ul>
              </div>
            </div>
          </Card>

          {selectedDecision ? (
            <div className="space-y-4">
              {/* 决策基本信息 */}
              <Card className="p-6">
                <div className="flex items-start justify-between mb-4">
                  <div>
                    <div className="flex items-center gap-2 mb-2">
                      <h3>决策详情</h3>
                      <Badge className={getLevelColor(selectedDecision.decisionLevel)}>
                        {selectedDecision.decisionLevel}
                      </Badge>
                      <Badge className={getStatusColor(selectedDecision.status)}>
                        {selectedDecision.status}
                      </Badge>
                    </div>
                    <p className="text-sm text-muted-foreground">决策编号: {selectedDecision.decisionNo}</p>
                  </div>
                  <Button variant="outline" onClick={() => setSelectedDecision(null)}>
                    返回列表
                  </Button>
                </div>

                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                  <div>
                    <Label>地块名称</Label>
                    <div className="field-value">{selectedDecision.fieldInfo.fieldName}</div>
                  </div>
                  <div>
                    <Label>作物类型</Label>
                    <div className="field-value">{selectedDecision.fieldInfo.cropType}</div>
                  </div>
                  <div>
                    <Label>生长阶段</Label>
                    <div className="field-value">{selectedDecision.fieldInfo.growthStage}</div>
                  </div>
                  <div>
                    <Label>地块面积</Label>
                    <div className="field-value">{selectedDecision.fieldInfo.area}亩</div>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4 mt-4">
                  <div>
                    <Label>决策类型</Label>
                    <div className="field-value flex items-center gap-2">
                      {getDecisionIcon(selectedDecision.decisionType)}
                      {selectedDecision.decisionType}
                    </div>
                  </div>
                  <div>
                    <Label>生成时间</Label>
                    <div className="field-value">{selectedDecision.generatedTime}</div>
                  </div>
                </div>

                {selectedDecision.deadline && (
                  <div className="mt-4">
                    <Label>执行截止时间</Label>
                    <div className="field-value text-orange-600 flex items-center gap-2">
                      <AlertCircle className="w-4 h-4" />
                      {selectedDecision.deadline}
                    </div>
                  </div>
                )}
              </Card>

              {/* 数据快照 */}
              <Card className="p-6">
                <h4 className="mb-4 flex items-center gap-2">
                  <Database className="w-5 h-5 text-blue-600" />
                  数据快照
                </h4>
                <div className="space-y-4">
                  {selectedDecision.dataSnapshot.map((snapshot, idx) => (
                    <Card key={idx} className="p-4 bg-blue-50">
                      <div className="flex items-center justify-between mb-3">
                        <h5 className="flex items-center gap-2">
                          <Info className="w-4 h-4 text-blue-600" />
                          {snapshot.source}
                        </h5>
                        <span className="text-xs text-muted-foreground">{snapshot.timestamp}</span>
                      </div>
                      <div className="grid grid-cols-3 gap-3">
                        {Object.entries(snapshot.values).map(([key, value]) => (
                          <div key={key} className="bg-white p-3 rounded">
                            <p className="text-xs text-muted-foreground mb-1">{key}</p>
                            <p className="text-sm font-medium">{value}</p>
                          </div>
                        ))}
                      </div>
                    </Card>
                  ))}
                </div>
              </Card>

              {/* 模型分析结果 */}
              <Card className="p-6">
                <h4 className="mb-4 flex items-center gap-2">
                  <Brain className="w-5 h-5 text-purple-600" />
                  模型分析结果
                </h4>
                <div className="grid grid-cols-2 gap-4 mb-4">
                  <div>
                    <Label>模型名称</Label>
                    <div className="field-value">{selectedDecision.modelAnalysis.modelName}</div>
                  </div>
                  <div>
                    <Label>模型版本</Label>
                    <div className="field-value">{selectedDecision.modelAnalysis.modelVersion}</div>
                  </div>
                </div>

                <div className="mb-4">
                  <Label>原始输出</Label>
                  <div className="field-value bg-purple-50">
                    <pre className="text-xs">{JSON.stringify(selectedDecision.modelAnalysis.rawOutput, null, 2)}</pre>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>置信度</Label>
                    <div className="field-value">
                      <div className="flex items-center gap-2">
                        <Progress value={selectedDecision.modelAnalysis.confidence * 100} className="flex-1" />
                        <span className="text-sm font-medium">{(selectedDecision.modelAnalysis.confidence * 100).toFixed(1)}%</span>
                      </div>
                    </div>
                  </div>
                  <div>
                    <Label>处理耗时</Label>
                    <div className="field-value">{selectedDecision.modelAnalysis.processingTime}秒</div>
                  </div>
                </div>
              </Card>

              {/* 规则逻辑 */}
              <Card className="p-6">
                <h4 className="mb-4 flex items-center gap-2">
                  <Layers className="w-5 h-5 text-green-600" />
                  规则逻辑与计算过程
                </h4>
                <div className="space-y-4">
                  {selectedDecision.ruleLogic.map((rule, idx) => (
                    <Card key={idx} className={`p-4 ${rule.matched ? 'bg-green-50 border-green-200' : 'bg-muted'}`}>
                      <div className="flex items-start justify-between mb-3">
                        <div className="flex items-center gap-2">
                          <div className={`w-6 h-6 rounded-full flex items-center justify-center ${
                            rule.matched ? 'bg-green-500' : 'bg-gray-400'
                          }`}>
                            {rule.matched ? (
                              <CheckCircle className="w-4 h-4 text-white" />
                            ) : (
                              <XCircle className="w-4 h-4 text-white" />
                            )}
                          </div>
                          <h5>{rule.ruleName}</h5>
                        </div>
                        <Badge variant="outline">{rule.ruleType}</Badge>
                      </div>

                      <div className="space-y-2">
                        <div>
                          <p className="text-xs text-muted-foreground mb-1">触发条件</p>
                          <code className="text-xs bg-white px-3 py-2 rounded block">
                            {rule.condition}
                          </code>
                        </div>

                        {rule.calculation && (
                          <div>
                            <p className="text-xs text-muted-foreground mb-1">计算过程</p>
                            <code className="text-xs bg-white px-3 py-2 rounded block">
                              {rule.calculation}
                            </code>
                          </div>
                        )}

                        {rule.result && (
                          <div>
                            <p className="text-xs text-muted-foreground mb-1">计算结果</p>
                            <div className="text-sm bg-white px-3 py-2 rounded">
                              {rule.result}
                            </div>
                          </div>
                        )}
                      </div>
                    </Card>
                  ))}
                </div>
              </Card>

              {/* 最终决策 */}
              <Card className="p-6">
                <h4 className="mb-4 flex items-center gap-2">
                  <Target className="w-5 h-5 text-orange-600" />
                  最终决策
                </h4>
                <div className="p-4 bg-green-50 rounded-lg border-2 border-green-200 mb-4">
                  <p className="text-sm">{selectedDecision.finalDecision}</p>
                </div>

                <div className="mb-4">
                  <Label>推理过程</Label>
                  <div className="field-value">
                    <p className="text-sm leading-relaxed">{selectedDecision.reasoning}</p>
                  </div>
                </div>

                <div>
                  <Label>综合置信度</Label>
                  <div className="field-value">
                    <div className="flex items-center gap-2">
                      <Progress value={selectedDecision.confidence * 100} className="flex-1" />
                      <span className="text-sm font-medium">{(selectedDecision.confidence * 100).toFixed(1)}%</span>
                    </div>
                  </div>
                </div>
              </Card>

              {/* 操作按钮 */}
              {selectedDecision.status === '待执行' && (
                <Card className="p-6">
                  <div className="flex gap-4">
                    <Button className="flex-1 bg-blue-600 hover:bg-blue-700" onClick={() => handleExecuteDecision(selectedDecision.id)}>
                      <Zap className="w-4 h-4 mr-2" />
                      执行决策
                    </Button>
                    <Button variant="outline" className="flex-1" onClick={() => handleIgnoreDecision(selectedDecision.id)}>
                      忽略决策
                    </Button>
                    <Button variant="outline">
                      <Download className="w-4 h-4 mr-2" />
                      导出报告
                    </Button>
                  </div>
                </Card>
              )}
            </div>
          ) : (
            <Card className="p-12">
              <div className="text-center">
                <Eye className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                <h4 className="text-muted-foreground mb-2">暂无选中的决策</h4>
                <p className="text-sm text-muted-foreground">
                  请从决策看板中选择一条决策查看详情
                </p>
                <Button className="mt-4" onClick={() => setActiveTab('dashboard')}>
                  前往决策看板
                </Button>
              </div>
            </Card>
          )}
        </TabsContent>
      </Tabs>
    </div>
  );
}
