import { useState } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs';
import { Input } from '../ui/input';
import { Label } from '../ui/label';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '../ui/dialog';
import { copyToClipboard } from '../../lib/clipboard';
import {
  Plug,
  CheckCircle,
  Clock,
  Search,
  Code,
  Server,
  Radio,
  Copy,
  Filter,
  ExternalLink,
  FileCode,
  Layers,
  Droplets,
  Bug,
  Sprout,
  Package,
  CloudRain,
  Activity,
  BarChart3,
  Zap,
  BookOpen,
  Terminal,
  Webhook,
  Key,
  PlayCircle,
  CheckCircle2,
  AlertCircle,
} from 'lucide-react';
import { toast } from 'sonner@2.0.3';

interface AIExternalIntegrationProps {
  activePath?: string;
}

// 决策类型
type DecisionType = '灌溉决策' | '施肥决策' | '病虫害防治' | '播种计划' | '收获计划' | '气象预警';

// 决策记录
interface DecisionRecord {
  id: string;
  decisionNo: string;
  title: string;
  type: DecisionType;
  fieldName: string;
  cropType: string;
  status: '待执行' | '执行中' | '已完成' | '已取消';
  priority: 'low' | 'medium' | 'high' | 'urgent';
  createdAt: string;
  apiPath: string;
  apiMethod: string;
  description: string;
  requestParams: any;
  responseExample: any;
  authRequired: boolean;
}

export function AIExternalIntegration({ activePath }: AIExternalIntegrationProps) {
  const [searchText, setSearchText] = useState('');
  const [filterType, setFilterType] = useState<string>('all');
  const [selectedDecision, setSelectedDecision] = useState<DecisionRecord | null>(null);
  const [activeTab, setActiveTab] = useState('list');
  const [showExampleDialog, setShowExampleDialog] = useState(false);
  const [exampleContent, setExampleContent] = useState('');
  const [exampleTitle, setExampleTitle] = useState('');

  // 决策列表数据
  const [decisions] = useState<DecisionRecord[]>([
    {
      id: 'dec_001',
      decisionNo: 'DEC-20241023-001',
      title: '1号大棚番茄开花期灌溉决策',
      type: '灌溉决策',
      fieldName: '1号大棚',
      cropType: '番茄',
      status: '已完成',
      priority: 'high',
      createdAt: '2024-10-23 14:30:00',
      apiPath: '/api/v1/decisions/irrigation/{decisionId}',
      apiMethod: 'GET',
      description: '获取灌溉决策详情，包含灌溉时间、水量、灌溉区域等信息',
      authRequired: true,
      requestParams: {
        decisionId: 'dec_001',
      },
      responseExample: {
        code: 200,
        message: 'success',
        data: {
          decisionId: 'dec_001',
          decisionNo: 'DEC-20241023-001',
          title: '1号大棚番茄开花期灌溉决策',
          type: 'irrigation',
          field: {
            fieldId: 'field_001',
            fieldName: '1号大棚',
            area: 2.5,
            cropType: '番茄',
            growthStage: '开花期',
          },
          irrigation: {
            waterAmount: 120,
            unit: 'mm',
            duration: 45,
            startTime: '17:00',
            endTime: '17:45',
            method: '滴灌',
            priority: 'high',
          },
          conditions: {
            soilMoisture: 45,
            temperature: 24.5,
            humidity: 68,
            weatherForecast: '晴',
          },
          recommendation: '根据土壤墒情和作物生长阶段，建议今日17:00进行灌溉，水量120mm，时长45分钟',
          confidence: 0.92,
          createdAt: '2024-10-23 14:30:00',
          status: 'completed',
        },
      },
    },
    {
      id: 'dec_002',
      decisionNo: 'DEC-20241023-002',
      title: '3号地块小麦施肥决策',
      type: '施肥决策',
      fieldName: '3号地块',
      cropType: '小麦',
      status: '待执行',
      priority: 'medium',
      createdAt: '2024-10-23 15:20:00',
      apiPath: '/api/v1/decisions/fertilization/{decisionId}',
      apiMethod: 'GET',
      description: '获取施肥决策详情，包含肥料种类、用量、施肥方式等信息',
      authRequired: true,
      requestParams: {
        decisionId: 'dec_002',
      },
      responseExample: {
        code: 200,
        message: 'success',
        data: {
          decisionId: 'dec_002',
          decisionNo: 'DEC-20241023-002',
          title: '3号地块小麦施肥决策',
          type: 'fertilization',
          field: {
            fieldId: 'field_003',
            fieldName: '3号地块',
            area: 5.0,
            cropType: '小麦',
            growthStage: '拔节期',
          },
          fertilization: {
            fertilizers: [
              {
                type: '尿素',
                amount: 50,
                unit: 'kg/亩',
                method: '撒施',
              },
              {
                type: '磷酸二铵',
                amount: 30,
                unit: 'kg/亩',
                method: '撒施',
              },
            ],
            totalCost: 1250,
            scheduledDate: '2024-10-25',
            weatherRequirement: '晴天或阴天，避免雨天',
          },
          soilAnalysis: {
            pH: 6.8,
            organicMatter: 2.3,
            nitrogen: 'medium',
            phosphorus: 'low',
            potassium: 'medium',
          },
          recommendation: '根据土壤养分分析，建议施用尿素50kg/亩和磷酸二铵30kg/亩，选择晴天或阴天施肥',
          confidence: 0.88,
          createdAt: '2024-10-23 15:20:00',
          status: 'pending',
        },
      },
    },
    {
      id: 'dec_003',
      decisionNo: 'DEC-20241023-003',
      title: '番茄晚疫病防治决策',
      type: '病虫害防治',
      fieldName: '1号大棚、2号大棚',
      cropType: '番茄',
      status: '执行中',
      priority: 'urgent',
      createdAt: '2024-10-23 10:15:00',
      apiPath: '/api/v1/decisions/pest-control/{decisionId}',
      apiMethod: 'GET',
      description: '获取病虫害防治决策详情，包含病虫害类型、防治措施、药剂配方等',
      authRequired: true,
      requestParams: {
        decisionId: 'dec_003',
      },
      responseExample: {
        code: 200,
        message: 'success',
        data: {
          decisionId: 'dec_003',
          decisionNo: 'DEC-20241023-003',
          title: '番茄晚疫病防治决策',
          type: 'pest_control',
          pest: {
            name: '番茄晚疫病',
            scientificName: 'Phytophthora infestans',
            severity: 'high',
            infectionRate: 15,
            affectedAreas: ['1号大棚', '2号大棚'],
          },
          control: {
            method: '化学防治',
            pesticides: [
              {
                name: '甲霜灵锰锌',
                concentration: '500倍液',
                dosage: '100ml/亩',
                safetyInterval: 7,
              },
            ],
            applicationMethod: '喷雾',
            frequency: '每7天一次，连续3次',
            weatherRequirement: '晴天或阴天，避免雨前喷药',
            protectiveEquipment: ['口罩', '手套', '防护服'],
          },
          prevention: {
            measures: [
              '加强通风，降低棚内湿度',
              '清除病叶病果',
              '避免傍晚浇水',
              '提高植株抗性',
            ],
          },
          estimatedCost: 850,
          recommendation: '立即实施化学防治，同时加强预防措施，控制病害蔓延',
          confidence: 0.95,
          createdAt: '2024-10-23 10:15:00',
          status: 'executing',
        },
      },
    },
    {
      id: 'dec_004',
      decisionNo: 'DEC-20241023-004',
      title: '4号地块玉米播种计划',
      type: '播种计划',
      fieldName: '4号地块',
      cropType: '玉米',
      status: '待执行',
      priority: 'medium',
      createdAt: '2024-10-23 09:00:00',
      apiPath: '/api/v1/decisions/sowing/{decisionId}',
      apiMethod: 'GET',
      description: '获取播种计划详情，包含播种时间、品种选择、播种密度等',
      authRequired: true,
      requestParams: {
        decisionId: 'dec_004',
      },
      responseExample: {
        code: 200,
        message: 'success',
        data: {
          decisionId: 'dec_004',
          decisionNo: 'DEC-20241023-004',
          title: '4号地块玉米播种计划',
          type: 'sowing',
          field: {
            fieldId: 'field_004',
            fieldName: '4号地块',
            area: 4.2,
            soilType: '壤土',
            previousCrop: '小麦',
          },
          sowing: {
            cropType: '玉米',
            variety: '先玉335',
            sowingDate: '2024-04-15',
            sowingMethod: '机械穴播',
            rowSpacing: 60,
            plantSpacing: 25,
            density: 4500,
            seedAmount: 3.5,
            depth: '3-5cm',
          },
          preparation: {
            tillage: '深耕25-30cm',
            baseFertilizer: [
              { name: '复合肥', amount: 50, unit: 'kg/亩' },
              { name: '有机肥', amount: 2000, unit: 'kg/亩' },
            ],
          },
          weatherRequirement: '土壤温度稳定在10℃以上，无霜期',
          recommendation: '建议4月中旬播种，选用优质种子，确保播种质量',
          confidence: 0.90,
          createdAt: '2024-10-23 09:00:00',
          status: 'pending',
        },
      },
    },
    {
      id: 'dec_005',
      decisionNo: 'DEC-20241023-005',
      title: '6号地块水稻收获计划',
      type: '收获计划',
      fieldName: '6号地块',
      cropType: '水稻',
      status: '待执行',
      priority: 'high',
      createdAt: '2024-10-23 08:30:00',
      apiPath: '/api/v1/decisions/harvest/{decisionId}',
      apiMethod: 'GET',
      description: '获取收获计划详情，包含收获时间、成熟度评估、收获方式等',
      authRequired: true,
      requestParams: {
        decisionId: 'dec_005',
      },
      responseExample: {
        code: 200,
        message: 'success',
        data: {
          decisionId: 'dec_005',
          decisionNo: 'DEC-20241023-005',
          title: '6号地块水稻收获计划',
          type: 'harvest',
          field: {
            fieldId: 'field_006',
            fieldName: '6号地块',
            area: 8.0,
            cropType: '水稻',
            variety: '南粳46',
            sowingDate: '2024-05-20',
          },
          harvest: {
            estimatedDate: '2024-10-28',
            maturity: {
              stage: '完熟期',
              progress: 95,
              grainMoisture: 22,
            },
            method: '联合收割机',
            estimatedYield: 550,
            unit: 'kg/亩',
            totalYield: 4400,
          },
          quality: {
            grainFullness: 'excellent',
            diseaseRate: 2,
            lodgingRate: 5,
            overallScore: 92,
          },
          postHarvest: {
            drying: '烘干至水分14%以下',
            storage: '通风仓储',
            transportation: '及时运输，避免雨淋',
          },
          weatherRequirement: '连续3天晴天，无降雨预报',
          recommendation: '根据成熟度和天气预报，建议10月28日开始收获',
          confidence: 0.93,
          createdAt: '2024-10-23 08:30:00',
          status: 'pending',
        },
      },
    },
    {
      id: 'dec_006',
      decisionNo: 'DEC-20241023-006',
      title: '强降雨防护决策',
      type: '气象预警',
      fieldName: '全部地块',
      cropType: '全部作物',
      status: '执行中',
      priority: 'urgent',
      createdAt: '2024-10-23 06:00:00',
      apiPath: '/api/v1/decisions/weather-alert/{decisionId}',
      apiMethod: 'GET',
      description: '获取气象预警决策详情，包含预警类型、影响范围、防护措施等',
      authRequired: true,
      requestParams: {
        decisionId: 'dec_006',
      },
      responseExample: {
        code: 200,
        message: 'success',
        data: {
          decisionId: 'dec_006',
          decisionNo: 'DEC-20241023-006',
          title: '强降雨防护决策',
          type: 'weather_alert',
          weather: {
            alertType: '暴雨预警',
            alertLevel: '橙色',
            startTime: '2024-10-24 02:00',
            endTime: '2024-10-24 08:00',
            rainfall: 50,
            windSpeed: 8,
            temperature: 18,
          },
          affectedAreas: [
            { fieldId: 'field_001', fieldName: '1号大棚', riskLevel: 'medium' },
            { fieldId: 'field_002', fieldName: '2号大棚', riskLevel: 'medium' },
            { fieldId: 'field_006', fieldName: '6号地块', riskLevel: 'high' },
          ],
          protection: {
            urgentMeasures: [
              '关闭所有大棚通风口',
              '检查并加固大棚骨架',
              '清理排水沟，确保排水畅通',
              '收割成熟作物，减少损失',
              '转移露天农资至室内',
            ],
            equipmentCheck: [
              '检查排水泵是否正常',
              '准备应急照明设备',
              '检查发电机燃油',
            ],
            postRainTasks: [
              '及时排除积水',
              '检查作物倒伏情况',
              '清理杂物和落叶',
              '防止病害爆发',
            ],
          },
          estimatedImpact: {
            riskLevel: 'high',
            potentialLoss: 15000,
            affectedCrops: ['番茄', '黄瓜', '水稻'],
          },
          recommendation: '立即启动应急预案，重点保护设施大棚和待收割作物',
          confidence: 0.96,
          createdAt: '2024-10-23 06:00:00',
          status: 'executing',
        },
      },
    },
  ]);

  // 筛选决策
  const filteredDecisions = decisions.filter(decision => {
    if (filterType !== 'all' && decision.type !== filterType) return false;
    if (searchText && !decision.title.toLowerCase().includes(searchText.toLowerCase()) &&
        !decision.decisionNo.toLowerCase().includes(searchText.toLowerCase())) return false;
    return true;
  });

  // 获取类型图标
  const getTypeIcon = (type: DecisionType) => {
    const icons = {
      '灌溉决策': Droplets,
      '施肥决策': Sprout,
      '病虫害防治': Bug,
      '播种计划': Package,
      '收获计划': BarChart3,
      '气象预警': CloudRain,
    };
    return icons[type] || Activity;
  };

  // 获取优先级标签
  const getPriorityBadge = (priority: string) => {
    const config = {
      low: { label: '低', className: 'bg-muted text-muted-foreground' },
      medium: { label: '中', className: 'bg-info-muted text-info-muted-foreground' },
      high: { label: '高', className: 'bg-warning-muted text-warning-muted-foreground' },
      urgent: { label: '紧急', className: 'bg-error-muted text-error-muted-foreground' },
    };
    const { label, className } = config[priority as keyof typeof config] || config.medium;
    return <Badge variant="outline" className={className}>{label}</Badge>;
  };

  // 获取状态标签
  const getStatusBadge = (status: string) => {
    const config = {
      '待执行': { className: 'bg-warning-muted text-warning-muted-foreground' },
      '执行中': { className: 'bg-info-muted text-info-muted-foreground' },
      '已完成': { className: 'bg-success-muted text-success-muted-foreground' },
      '已取消': { className: 'bg-muted text-muted-foreground' },
    };
    const { className } = config[status as keyof typeof config] || config['待执行'];
    return <Badge variant="outline" className={className}>{status}</Badge>;
  };

  // 显示API示例
  const handleCopyAPI = (decision: DecisionRecord, type: 'curl' | 'url' | 'request' | 'response') => {
    let content = '';
    const baseUrl = 'https://api.smart-farm.com';
    const apiUrl = `${baseUrl}${decision.apiPath.replace('{decisionId}', decision.id)}`;
    
    switch (type) {
      case 'url':
        content = apiUrl;
        break;
      case 'curl':
        content = `curl -X ${decision.apiMethod} "${apiUrl}" \\
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \\
  -H "Content-Type: application/json"`;
        break;
      case 'request':
        content = JSON.stringify({
          method: decision.apiMethod,
          url: apiUrl,
          headers: {
            'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
            'Content-Type': 'application/json',
          },
          params: decision.requestParams,
        }, null, 2);
        break;
      case 'response':
        content = JSON.stringify(decision.responseExample, null, 2);
        break;
    }

    let title = '';
    switch (type) {
      case 'url':
        title = 'API URL';
        break;
      case 'curl':
        title = 'cURL示例';
        break;
      case 'request':
        title = '请求示例';
        break;
      case 'response':
        title = '响应示例';
        break;
    }

    setExampleTitle(title);
    setExampleContent(content);
    setShowExampleDialog(true);
  };

  // 测试API
  const handleTestAPI = (decision: DecisionRecord) => {
    toast.info(`正在测试 ${decision.title} 的API接口...`);
    setTimeout(() => {
      toast.success('API测试成功！响应时间: 156ms');
    }, 1000);
  };

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <Card className="p-6 bg-gradient-to-r from-info-muted to-info-muted/50 border-info">
        <div className="flex items-start gap-3">
          <Plug className="w-6 h-6 text-info flex-shrink-0 mt-1" />
          <div className="flex-1">
            <h2 className="mb-2">外部系统联动</h2>
            <p className="text-sm text-muted-foreground mb-3">
              为每个决策提供标准的RESTful API接口，支持外部系统通过HTTP请求获取决策详情，实现系统间无缝对接
            </p>
            <div className="flex flex-wrap gap-2">
              <Badge variant="outline" className="bg-white">
                <Code className="w-3 h-3 mr-1" />
                RESTful API
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Server className="w-3 h-3 mr-1" />
                标准接口
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Webhook className="w-3 h-3 mr-1" />
                实时调用
              </Badge>
              <Badge variant="outline" className="bg-white">
                <Key className="w-3 h-3 mr-1" />
                安全认证
              </Badge>
            </div>
          </div>
        </div>
      </Card>

      {/* Tab切换 */}
      <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
        <TabsList>
          <TabsTrigger value="list">
            <Layers className="w-4 h-4 mr-2" />
            决策列表
          </TabsTrigger>
          <TabsTrigger value="docs">
            <BookOpen className="w-4 h-4 mr-2" />
            接口文档
          </TabsTrigger>
          <TabsTrigger value="examples">
            <Terminal className="w-4 h-4 mr-2" />
            调用示例
          </TabsTrigger>
        </TabsList>

        {/* 决策列表 */}
        <TabsContent value="list">
          <Card className="p-6">
            {/* 筛选栏 */}
            <div className="flex gap-4 mb-6">
              <div className="flex-1">
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <Input
                    placeholder="搜索决策编号或标题..."
                    value={searchText}
                    onChange={(e) => setSearchText(e.target.value)}
                    className="pl-10"
                  />
                </div>
              </div>
              <div className="w-48">
                <select
                  value={filterType}
                  onChange={(e) => setFilterType(e.target.value)}
                  className="w-full h-10 px-3 rounded-md border border-input bg-background"
                >
                  <option value="all">全部类型</option>
                  <option value="灌溉决策">灌溉决策</option>
                  <option value="施肥决策">施肥决策</option>
                  <option value="病虫害防治">病虫害防治</option>
                  <option value="播种计划">播种计划</option>
                  <option value="收获计划">收获计划</option>
                  <option value="气象预警">气象预警</option>
                </select>
              </div>
            </div>

            {/* 决策列表 */}
            <div className="space-y-4">
              {filteredDecisions.map((decision) => {
                const TypeIcon = getTypeIcon(decision.type);
                const baseUrl = 'https://api.smart-farm.com';
                const apiUrl = `${baseUrl}${decision.apiPath.replace('{decisionId}', decision.id)}`;

                return (
                  <div key={decision.id} className="border rounded-lg p-5 hover:shadow-md transition-shadow">
                    {/* 决策头部信息 */}
                    <div className="flex items-start gap-4 mb-4">
                      <div className="w-12 h-12 rounded-lg bg-gradient-to-br from-blue-100 to-cyan-100 flex items-center justify-center flex-shrink-0">
                        <TypeIcon className="w-6 h-6 text-blue-600" />
                      </div>

                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 mb-2">
                          <h4 className="truncate">{decision.title}</h4>
                          <Badge variant="outline" className="text-xs whitespace-nowrap">
                            {decision.decisionNo}
                          </Badge>
                        </div>

                        <div className="flex flex-wrap items-center gap-2 mb-3">
                          <Badge variant="outline">{decision.type}</Badge>
                          {getStatusBadge(decision.status)}
                          {getPriorityBadge(decision.priority)}
                          <Badge variant="outline" className="text-xs">
                            {decision.fieldName}
                          </Badge>
                          <Badge variant="outline" className="text-xs">
                            {decision.cropType}
                          </Badge>
                        </div>

                        <p className="text-sm text-muted-foreground mb-3">
                          {decision.description}
                        </p>

                        <div className="text-xs text-muted-foreground">
                          创建时间: {decision.createdAt}
                        </div>
                      </div>
                    </div>

                    {/* API接口信息 */}
                    <div className="bg-muted rounded-lg p-4 space-y-3">
                      <div className="flex items-center gap-2">
                        <FileCode className="w-4 h-4 text-blue-600" />
                        <span className="text-sm font-medium">API接口</span>
                        {decision.authRequired && (
                          <Badge variant="outline" className="text-xs bg-yellow-50 text-yellow-700 border-yellow-300">
                            <Key className="w-3 h-3 mr-1" />
                            需要认证
                          </Badge>
                        )}
                      </div>

                      {/* 请求方法和路径 */}
                      <div className="flex items-center gap-2">
                        <Badge className={decision.apiMethod === 'GET' ? 'bg-green-600' : 'bg-blue-600'}>
                          {decision.apiMethod}
                        </Badge>
                        <code className="flex-1 px-3 py-2 bg-background rounded border text-sm font-mono break-all">
                          {apiUrl}
                        </code>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleCopyAPI(decision, 'url')}
                        >
                          <Copy className="w-3 h-3 mr-1" />
                          复制
                        </Button>
                      </div>

                      {/* 快捷操作 */}
                      <div className="flex gap-2 pt-2 border-t">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleCopyAPI(decision, 'curl')}
                        >
                          <Terminal className="w-3 h-3 mr-1" />
                          cURL示例
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleCopyAPI(decision, 'request')}
                        >
                          <Code className="w-3 h-3 mr-1" />
                          请求示例
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleCopyAPI(decision, 'response')}
                        >
                          <FileCode className="w-3 h-3 mr-1" />
                          响应示例
                        </Button>
                        <Button
                          size="sm"
                          onClick={() => handleTestAPI(decision)}
                          className="bg-blue-600 hover:bg-blue-700 ml-auto"
                        >
                          <PlayCircle className="w-3 h-3 mr-1" />
                          测试API
                        </Button>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>

            {filteredDecisions.length === 0 && (
              <div className="text-center py-12 text-muted-foreground">
                <FileCode className="w-12 h-12 mx-auto mb-3 opacity-50" />
                <p>暂无匹配的决策</p>
              </div>
            )}
          </Card>
        </TabsContent>

        {/* 接口文档 */}
        <TabsContent value="docs">
          <Card className="p-6">
            <h3 className="mb-4">RESTful API接口文档</h3>

            <div className="space-y-6">
              {/* 基本信息 */}
              <div className="p-4 bg-blue-50 rounded-lg border border-blue-200">
                <h4 className="mb-3">基本信息</h4>
                <div className="space-y-2 text-sm">
                  <div className="flex gap-2">
                    <span className="font-medium w-24">接口域名:</span>
                    <code className="text-blue-600">https://api.smart-farm.com</code>
                  </div>
                  <div className="flex gap-2">
                    <span className="font-medium w-24">API版本:</span>
                    <code>v1</code>
                  </div>
                  <div className="flex gap-2">
                    <span className="font-medium w-24">数据格式:</span>
                    <code>JSON</code>
                  </div>
                  <div className="flex gap-2">
                    <span className="font-medium w-24">字符编码:</span>
                    <code>UTF-8</code>
                  </div>
                </div>
              </div>

              {/* 认证方式 */}
              <div className="p-4 bg-yellow-50 rounded-lg border border-yellow-200">
                <h4 className="mb-3 flex items-center gap-2">
                  <Key className="w-4 h-4" />
                  认证方式
                </h4>
                <p className="text-sm text-muted-foreground mb-3">
                  所有API接口调用都需要在请求头中包含访问令牌（Access Token）进行身份验证
                </p>
                <div className="bg-white rounded p-3 border">
                  <code className="text-sm">
                    Authorization: Bearer YOUR_ACCESS_TOKEN
                  </code>
                </div>
                <p className="text-xs text-muted-foreground mt-2">
                  请联系系统管理员获取您的访问令牌
                </p>
              </div>

              {/* 请求示例 */}
              <div className="p-4 bg-green-50 rounded-lg border border-green-200">
                <h4 className="mb-3">请求示例</h4>
                <pre className="bg-white rounded p-4 border text-xs overflow-x-auto">
{`GET /api/v1/decisions/irrigation/dec_001 HTTP/1.1
Host: api.smart-farm.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json
Accept: application/json`}
                </pre>
              </div>

              {/* 响应格式 */}
              <div className="p-4 bg-purple-50 rounded-lg border border-purple-200">
                <h4 className="mb-3">响应格式</h4>
                <p className="text-sm text-muted-foreground mb-3">
                  所有API接口返回统一的JSON格式响应
                </p>
                <pre className="bg-white rounded p-4 border text-xs overflow-x-auto">
{`{
  "code": 200,           // 状态码: 200=成功, 400=参数错误, 401=未授权, 404=未找到, 500=服务器错误
  "message": "success",  // 消息描述
  "data": {              // 响应数据
    // 具体的决策数据
  }
}`}
                </pre>
              </div>

              {/* 错误码说明 */}
              <div className="p-4 bg-red-50 rounded-lg border border-red-200">
                <h4 className="mb-3">错误码说明</h4>
                <div className="space-y-2 text-sm">
                  <div className="flex gap-2">
                    <code className="font-medium w-16">200</code>
                    <span>请求成功</span>
                  </div>
                  <div className="flex gap-2">
                    <code className="font-medium w-16">400</code>
                    <span>请求参数错误</span>
                  </div>
                  <div className="flex gap-2">
                    <code className="font-medium w-16">401</code>
                    <span>未授权，访问令牌无效或已过期</span>
                  </div>
                  <div className="flex gap-2">
                    <code className="font-medium w-16">404</code>
                    <span>请求的资源不存在</span>
                  </div>
                  <div className="flex gap-2">
                    <code className="font-medium w-16">429</code>
                    <span>请求过于频繁，请稍后重试</span>
                  </div>
                  <div className="flex gap-2">
                    <code className="font-medium w-16">500</code>
                    <span>服务器内部错误</span>
                  </div>
                </div>
              </div>

              {/* 频率限制 */}
              <div className="p-4 bg-muted rounded-lg border">
                <h4 className="mb-3">频率限制</h4>
                <div className="space-y-2 text-sm">
                  <div className="flex gap-2">
                    <Zap className="w-4 h-4 text-yellow-600 flex-shrink-0 mt-0.5" />
                    <div>
                      <p className="font-medium">每个令牌限制：100次/分钟</p>
                      <p className="text-xs text-muted-foreground mt-1">
                        超出限制将返回429错误，响应头中包含 X-RateLimit-Reset 字段，表示下次可用时间
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </Card>
        </TabsContent>

        {/* 调用示例 */}
        <TabsContent value="examples">
          <Card className="p-6">
            <h3 className="mb-4">API调用示例</h3>

            <div className="space-y-6">
              {/* cURL示例 */}
              <div>
                <h4 className="mb-3 flex items-center gap-2">
                  <Terminal className="w-4 h-4" />
                  cURL 命令
                </h4>
                <div className="bg-foreground text-background rounded-lg p-4">
                  <pre className="text-xs overflow-x-auto">
{`# 获取灌溉决策详情
curl -X GET "https://api.smart-farm.com/api/v1/decisions/irrigation/dec_001" \\
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \\
  -H "Content-Type: application/json"

# 获取施肥决策详情
curl -X GET "https://api.smart-farm.com/api/v1/decisions/fertilization/dec_002" \\
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \\
  -H "Content-Type: application/json"`}
                  </pre>
                </div>
              </div>

              {/* JavaScript示例 */}
              <div>
                <h4 className="mb-3">JavaScript (Fetch API)</h4>
                <div className="bg-foreground text-background rounded-lg p-4">
                  <pre className="text-xs overflow-x-auto">
{`// 获取决策详情
async function getDecisionDetail(decisionId, type) {
  const response = await fetch(
    \`https://api.smart-farm.com/api/v1/decisions/\${type}/\${decisionId}\`,
    {
      method: 'GET',
      headers: {
        'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
        'Content-Type': 'application/json'
      }
    }
  );
  
  if (!response.ok) {
    throw new Error(\`HTTP error! status: \${response.status}\`);
  }
  
  const data = await response.json();
  return data;
}

// 使用示例
getDecisionDetail('dec_001', 'irrigation')
  .then(data => {
    console.log('决策详情:', data);
  })
  .catch(error => {
    console.error('请求失败:', error);
  });`}
                  </pre>
                </div>
              </div>

              {/* Python示例 */}
              <div>
                <h4 className="mb-3">Python (requests库)</h4>
                <div className="bg-foreground text-background rounded-lg p-4">
                  <pre className="text-xs overflow-x-auto">
{`import requests
import json

# 配置
BASE_URL = "https://api.smart-farm.com/api/v1"
ACCESS_TOKEN = "YOUR_ACCESS_TOKEN"

# 设置请求头
headers = {
    "Authorization": f"Bearer {ACCESS_TOKEN}",
    "Content-Type": "application/json"
}

# 获取决策详情
def get_decision_detail(decision_id, decision_type):
    url = f"{BASE_URL}/decisions/{decision_type}/{decision_id}"
    response = requests.get(url, headers=headers)
    
    if response.status_code == 200:
        return response.json()
    else:
        raise Exception(f"API请求失败: {response.status_code}")

# 使用示例
try:
    decision = get_decision_detail("dec_001", "irrigation")
    print("决策详情:", json.dumps(decision, indent=2, ensure_ascii=False))
except Exception as e:
    print("错误:", str(e))`}
                  </pre>
                </div>
              </div>

              {/* Java示例 */}
              <div>
                <h4 className="mb-3">Java (HttpURLConnection)</h4>
                <div className="bg-foreground text-background rounded-lg p-4">
                  <pre className="text-xs overflow-x-auto">
{`import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class DecisionAPIClient {
    private static final String BASE_URL = "https://api.smart-farm.com/api/v1";
    private static final String ACCESS_TOKEN = "YOUR_ACCESS_TOKEN";
    
    public static String getDecisionDetail(String decisionId, String type) throws Exception {
        String url = BASE_URL + "/decisions/" + type + "/" + decisionId;
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        
        // 设置请求方法和头部
        con.setRequestMethod("GET");
        con.setRequestProperty("Authorization", "Bearer " + ACCESS_TOKEN);
        con.setRequestProperty("Content-Type", "application/json");
        
        // 读取响应
        BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream())
        );
        String inputLine;
        StringBuffer response = new StringBuffer();
        
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        
        return response.toString();
    }
    
    public static void main(String[] args) {
        try {
            String result = getDecisionDetail("dec_001", "irrigation");
            System.out.println("决策详情: " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}`}
                  </pre>
                </div>
              </div>

              {/* 注意事项 */}
              <div className="p-4 bg-yellow-50 rounded-lg border border-yellow-200">
                <h4 className="mb-3 flex items-center gap-2">
                  <AlertCircle className="w-4 h-4" />
                  注意事项
                </h4>
                <ul className="space-y-2 text-sm text-muted-foreground">
                  <li className="flex gap-2">
                    <CheckCircle2 className="w-4 h-4 text-green-600 flex-shrink-0 mt-0.5" />
                    <span>请妥善保管访问令牌，不要泄露给他人</span>
                  </li>
                  <li className="flex gap-2">
                    <CheckCircle2 className="w-4 h-4 text-green-600 flex-shrink-0 mt-0.5" />
                    <span>建议实现请求失败重试机制，提高调用成功率</span>
                  </li>
                  <li className="flex gap-2">
                    <CheckCircle2 className="w-4 h-4 text-green-600 flex-shrink-0 mt-0.5" />
                    <span>注意遵守API频率限制，避免被限流</span>
                  </li>
                  <li className="flex gap-2">
                    <CheckCircle2 className="w-4 h-4 text-green-600 flex-shrink-0 mt-0.5" />
                    <span>建议在生产环境中使用HTTPS协议确保数据传输安全</span>
                  </li>
                  <li className="flex gap-2">
                    <CheckCircle2 className="w-4 h-4 text-green-600 flex-shrink-0 mt-0.5" />
                    <span>建议实现错误处理和日志记录机制</span>
                  </li>
                </ul>
              </div>
            </div>
          </Card>
        </TabsContent>
      </Tabs>

      {/* API示例弹窗 */}
      <Dialog open={showExampleDialog} onOpenChange={setShowExampleDialog}>
        <DialogContent className="max-w-3xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{exampleTitle}</DialogTitle>
            <DialogDescription>
              点击下方复制按钮可复制内容到剪贴板
            </DialogDescription>
          </DialogHeader>
          
          <div className="mt-4">
            <div className="bg-foreground text-background rounded-lg p-4 relative">
              <Button
                size="sm"
                variant="outline"
                className="absolute top-2 right-2 bg-accent hover:bg-accent/80"
                onClick={async () => {
                  const success = await copyToClipboard(exampleContent);
                  if (success) {
                    toast.success('已复制到剪贴板');
                  } else {
                    toast.error('复制失败，请重试');
                  }
                }}
              >
                <Copy className="w-3 h-3 mr-1" />
                复制
              </Button>
              <pre className="text-xs overflow-x-auto pr-20 whitespace-pre-wrap break-words">
                {exampleContent}
              </pre>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
