/**
 * 土壤质量评价组件
 * 提供土壤质量分析、评价和改良建议功能
 */

'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 { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Textarea } from '@/components/ui/textarea';
import {
  BarChart3,
  TrendingUp,
  TrendingDown,
  Activity,
  AlertCircle,
  CheckCircle,
  Info,
  Droplets,
  Leaf,
  Zap,
  Beaker,
  Calculator,
  FileText,
  Calendar,
  MapPin,
  User,
  Download,
  RefreshCw,
  Eye,
  Settings,
  Target,
  Award,
  AlertTriangle,
  ThumbsUp
} from 'lucide-react';
import { toast } from 'sonner';
import {
  SoilQualityService,
  SoilQualityEvaluation,
  SoilIndicator,
  SoilRecommendation,
  SoilQualityHistory,
  SoilAnalysisForm,
  formatSoilScore,
  getSoilGradeColor,
  getIndicatorStatusColor,
  formatDate
} from './soilQualityService';
import {
  SOIL_TYPES,
  SOIL_TEXTURES,
  DRAINAGE_LEVELS
} from './soilTypes';

export function SoilQualityAnalysis() {
  const [activeTab, setActiveTab] = useState<'analysis' | 'evaluation' | 'history' | 'recommendations'>('analysis');
  const [selectedField, setSelectedField] = useState('field-1');
  const [isLoading, setIsLoading] = useState(false);
  const [currentEvaluation, setCurrentEvaluation] = useState<SoilQualityEvaluation | null>(null);
  const [historicalData, setHistoricalData] = useState<SoilQualityHistory[]>([]);
  const [showForm, setShowForm] = useState(false);

  // 表单数据
  const [formData, setFormData] = useState<SoilAnalysisForm>({
    fieldId: 'field-1',
    sampleDate: new Date().toISOString().split('T')[0],
    sampleDepth: 20,
    ph: 6.5,
    organicMatter: 2.5,
    nitrogen: 1.2,
    phosphorus: 18,
    potassium: 120,
    calcium: 1200,
    magnesium: 250,
    sulfur: 15,
    iron: 10,
    manganese: 5,
    zinc: 2,
    copper: 1,
    boron: 0.8,
    soilTexture: 'medium',
    drainage: 'good',
    notes: ''
  });

  // 模拟地块数据
  const mockFields = [
    { id: 'field-1', name: '东区1号地', code: 'DB001', area: 85.5 },
    { id: 'field-2', name: '西区2号地', code: 'DB002', area: 92.3 },
    { id: 'field-3', name: '南区3号地', code: 'DB003', area: 78.7 },
  ];

  // 初始化数据
  useEffect(() => {
    loadHistoricalData();
  }, [selectedField]);

  const loadHistoricalData = () => {
    const history = SoilQualityService.getHistoricalData(selectedField);
    setHistoricalData(history);

    // 如果有历史记录，显示最新的评价
    if (history.length > 0) {
      setCurrentEvaluation(history[0].evaluation);
    }
  };

  const handleFormSubmit = async () => {
    setIsLoading(true);
    try {
      // 生成土壤质量评价
      const evaluation = SoilQualityService.generateEvaluation(formData);
      setCurrentEvaluation(evaluation);

      // 更新历史数据
      const newHistory: SoilQualityHistory = {
        date: evaluation.date,
        overallScore: evaluation.overallScore,
        indicatorChanges: [],
        evaluation
      };

      setHistoricalData([newHistory, ...historicalData]);
      setShowForm(false);
      setActiveTab('evaluation');

      toast.success('土壤质量评价完成！');
    } catch (error) {
      toast.error('评价失败，请检查数据');
    } finally {
      setIsLoading(false);
    }
  };

  const handleInputChange = (field: keyof SoilAnalysisForm, value: any) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };

  const exportReport = () => {
    if (!currentEvaluation) {
      toast.error('没有可导出的评价报告');
      return;
    }

    // 模拟导出功能
    toast.success('正在生成土壤质量评价报告...');
    setTimeout(() => {
      toast.success('报告已生成并下载');
    }, 2000);
  };

  const getPriorityColor = (priority: string): string => {
    switch (priority) {
      case 'high': return 'text-red-600 dark:text-red-400';
      case 'medium': return 'text-yellow-600 dark:text-yellow-400';
      case 'low': return 'text-green-600 dark:text-green-400';
      default: return 'text-gray-600 dark:text-gray-400';
    }
  };

  const getPriorityBadgeVariant = (priority: string): string => {
    switch (priority) {
      case 'high': return 'destructive';
      case 'medium': return 'default';
      case 'low': return 'secondary';
      default: return 'outline';
    }
  };

  return (
    <div className="space-y-6">
      {/* 页面头部 */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800 dark:text-green-200">土壤质量评价</h2>
          <p className="text-muted-foreground">
            专业的土壤质量分析与改良建议系统
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={() => setShowForm(!showForm)}>
            <Calculator className="w-4 h-4 mr-2" />
            {showForm ? '隐藏表单' : '新建评价'}
          </Button>
          <Button variant="outline" onClick={loadHistoricalData}>
            <RefreshCw className="w-4 h-4 mr-2" />
            刷新数据
          </Button>
          <Button variant="outline" onClick={exportReport} disabled={!currentEvaluation}>
            <Download className="w-4 h-4 mr-2" />
            导出报告
          </Button>
        </div>
      </div>

      {/* 地块信息卡片 */}
      <div className="grid grid-cols-4 gap-4">
        <Card className="p-4 bg-gradient-to-br from-green-50 to-blue-50 dark:from-green-950 dark:to-blue-950">
          <div className="flex items-center gap-3">
            <MapPin className="w-8 h-8 text-green-600 dark:text-green-400" />
            <div>
              <div className="text-sm text-muted-foreground">当前地块</div>
              <div className="font-medium">{mockFields.find(f => f.id === selectedField)?.name}</div>
            </div>
          </div>
        </Card>
        <Card className="p-4 bg-card">
          <div className="flex items-center gap-3">
            <Award className="w-8 h-8 text-blue-600 dark:text-blue-400" />
            <div>
              <div className="text-sm text-muted-foreground">总体评分</div>
              <div
                className="font-bold text-lg"
                style={{ color: currentEvaluation ? getSoilGradeColor(currentEvaluation.overallGrade) : '#6b7280' }}
              >
                {currentEvaluation ? formatSoilScore(currentEvaluation.overallScore) : '--'}
              </div>
            </div>
          </div>
        </Card>
        <Card className="p-4 bg-card">
          <div className="flex items-center gap-3">
            <Activity className="w-8 h-8 text-purple-600 dark:text-purple-400" />
            <div>
              <div className="text-sm text-muted-foreground">质量等级</div>
              <div
                className="font-bold text-lg"
                style={{ color: currentEvaluation ? getSoilGradeColor(currentEvaluation.overallGrade) : '#6b7280' }}
              >
                {currentEvaluation ? currentEvaluation.overallGrade : '--'}
              </div>
            </div>
          </div>
        </Card>
        <Card className="p-4 bg-card">
          <div className="flex items-center gap-3">
            <FileText className="w-8 h-8 text-orange-600 dark:text-orange-400" />
            <div>
              <div className="text-sm text-muted-foreground">历史记录</div>
              <div className="font-medium">{historicalData.length} 条</div>
            </div>
          </div>
        </Card>
      </div>

      {/* 土壤分析表单 */}
      {showForm && (
        <Card className="p-6 bg-card">
          <div className="flex items-center justify-between mb-6">
            <h3 className="text-lg font-semibold">土壤质量分析表单</h3>
            <Button variant="outline" size="sm" onClick={() => setShowForm(false)}>
              <Eye className="w-4 h-4 mr-2" />
              查看评价结果
            </Button>
          </div>

          <div className="grid grid-cols-2 gap-6">
            {/* 基本信息 */}
            <div className="space-y-4">
              <h4 className="font-medium">基本信息</h4>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="fieldId">地块选择</Label>
                  <Select value={formData.fieldId} onValueChange={(value) => handleInputChange('fieldId', value)}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {mockFields.map(field => (
                        <SelectItem key={field.id} value={field.id}>
                          {field.name} ({field.code})
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label htmlFor="sampleDate">取样日期</Label>
                  <Input
                    id="sampleDate"
                    type="date"
                    value={formData.sampleDate}
                    onChange={(e) => handleInputChange('sampleDate', e.target.value)}
                  />
                </div>
                <div>
                  <Label htmlFor="sampleDepth">取样深度 (cm)</Label>
                  <Input
                    id="sampleDepth"
                    type="number"
                    value={formData.sampleDepth}
                    onChange={(e) => handleInputChange('sampleDepth', Number(e.target.value))}
                  />
                </div>
                <div>
                  <Label htmlFor="soilTexture">土壤质地</Label>
                  <Select value={formData.soilTexture} onValueChange={(value) => handleInputChange('soilTexture', value)}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {SOIL_TEXTURES.map(texture => (
                        <SelectItem key={texture.id} value={texture.id}>
                          {texture.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label htmlFor="drainage">排水条件</Label>
                  <Select value={formData.drainage} onValueChange={(value) => handleInputChange('drainage', value)}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      {DRAINAGE_LEVELS.map(level => (
                        <SelectItem key={level.id} value={level.id}>
                          {level.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </div>

            {/* 化学指标 */}
            <div className="space-y-4">
              <h4 className="font-medium">化学指标</h4>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="ph">pH值</Label>
                  <Input
                    id="ph"
                    type="number"
                    step="0.1"
                    value={formData.ph}
                    onChange={(e) => handleInputChange('ph', Number(e.target.value))}
                  />
                </div>
                <div>
                  <Label htmlFor="organicMatter">有机质 (%)</Label>
                  <Input
                    id="organicMatter"
                    type="number"
                    step="0.1"
                    value={formData.organicMatter}
                    onChange={(e) => handleInputChange('organicMatter', Number(e.target.value))}
                  />
                </div>
                <div>
                  <Label htmlFor="nitrogen">全氮 (g/kg)</Label>
                  <Input
                    id="nitrogen"
                    type="number"
                    step="0.1"
                    value={formData.nitrogen}
                    onChange={(e) => handleInputChange('nitrogen', Number(e.target.value))}
                  />
                </div>
                <div>
                  <Label htmlFor="phosphorus">有效磷 (mg/kg)</Label>
                  <Input
                    id="phosphorus"
                    type="number"
                    step="1"
                    value={formData.phosphorus}
                    onChange={(e) => handleInputChange('phosphorus', Number(e.target.value))}
                  />
                </div>
                <div>
                  <Label htmlFor="potassium">速效钾 (mg/kg)</Label>
                  <Input
                    id="potassium"
                    type="number"
                    step="1"
                    value={formData.potassium}
                    onChange={(e) => handleInputChange('potassium', Number(e.target.value))}
                  />
                </div>
                <div>
                  <Label htmlFor="notes">备注</Label>
                  <Textarea
                    id="notes"
                    value={formData.notes}
                    onChange={(e) => handleInputChange('notes', e.target.value)}
                    placeholder="请输入其他相关信息..."
                  />
                </div>
              </div>
            </div>
          </div>

          <div className="flex justify-end mt-6">
            <Button onClick={handleFormSubmit} disabled={isLoading}>
              {isLoading ? (
                <>
                  <RefreshCw className="w-4 h-4 mr-2 animate-spin" />
                  分析中...
                </>
              ) : (
                <>
                  <Calculator className="w-4 h-4 mr-2" />
                  生成评价
                </>
              )}
            </Button>
          </div>
        </Card>
      )}

      {/* 主要内容区域 */}
      <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as any)}>
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="analysis">指标分析</TabsTrigger>
          <TabsTrigger value="evaluation">评价结果</TabsTrigger>
          <TabsTrigger value="recommendations">改良建议</TabsTrigger>
          <TabsTrigger value="history">历史记录</TabsTrigger>
        </TabsList>

        {/* 指标分析 */}
        <TabsContent value="analysis" className="space-y-4">
          {currentEvaluation ? (
            <div className="grid grid-cols-2 gap-6">
              {/* 主要指标 */}
              <Card className="p-6 bg-card">
                <h3 className="mb-4">主要指标得分</h3>
                <div className="space-y-4">
                  {currentEvaluation.indicators
                    .filter(ind => ['ph', 'organicMatter', 'nitrogen', 'phosphorus', 'potassium'].includes(ind.id))
                    .map(indicator => (
                    <div key={indicator.id} className="flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        <div
                          className="w-3 h-3 rounded-full"
                          style={{ backgroundColor: getIndicatorStatusColor(indicator.status) }}
                        />
                        <div>
                          <div className="font-medium">{indicator.name}</div>
                          <div className="text-sm text-muted-foreground">
                            {indicator.value} {indicator.unit}
                          </div>
                        </div>
                      </div>
                      <div className="text-right">
                        <div className="font-bold">{indicator.score}分</div>
                        <Badge
                          variant="outline"
                          className="font-light"
                          style={{
                            backgroundColor: `${getIndicatorStatusColor(indicator.status)}20`,
                            borderColor: getIndicatorStatusColor(indicator.status),
                            color: getIndicatorStatusColor(indicator.status)
                          }}
                        >
                          {indicator.status === 'excellent' && '优秀'}
                          {indicator.status === 'good' && '良好'}
                          {indicator.status === 'moderate' && '中等'}
                          {indicator.status === 'poor' && '较差'}
                          {indicator.status === 'very_poor' && '很差'}
                        </Badge>
                      </div>
                    </div>
                  ))}
                </div>
              </Card>

              {/* 微量元素 */}
              <Card className="p-6 bg-card">
                <h3 className="mb-4">微量元素得分</h3>
                <div className="space-y-4">
                  {currentEvaluation.indicators
                    .filter(ind => ['iron', 'manganese', 'zinc', 'copper', 'boron'].includes(ind.id))
                    .map(indicator => (
                    <div key={indicator.id} className="flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        <div
                          className="w-3 h-3 rounded-full"
                          style={{ backgroundColor: getIndicatorStatusColor(indicator.status) }}
                        />
                        <div>
                          <div className="font-medium">{indicator.name}</div>
                          <div className="text-sm text-muted-foreground">
                            {indicator.value} {indicator.unit}
                          </div>
                        </div>
                      </div>
                      <div className="text-right">
                        <div className="font-bold">{indicator.score}分</div>
                        <Badge
                          variant="outline"
                          className="font-light"
                          style={{
                            backgroundColor: `${getIndicatorStatusColor(indicator.status)}20`,
                            borderColor: getIndicatorStatusColor(indicator.status),
                            color: getIndicatorStatusColor(indicator.status)
                          }}
                        >
                          {indicator.status === 'excellent' && '优秀'}
                          {indicator.status === 'good' && '良好'}
                          {indicator.status === 'moderate' && '中等'}
                          {indicator.status === 'poor' && '较差'}
                          {indicator.status === 'very_poor' && '很差'}
                        </Badge>
                      </div>
                    </div>
                  ))}
                </div>
              </Card>
            </div>
          ) : (
            <Card className="p-8 text-center bg-card">
              <Beaker className="w-16 h-16 mx-auto text-muted-foreground mb-4" />
              <h3 className="text-lg font-semibold mb-2">暂无评价数据</h3>
              <p className="text-muted-foreground mb-4">
                请先填写土壤分析表单生成评价报告
              </p>
              <Button onClick={() => setShowForm(true)}>
                <Calculator className="w-4 h-4 mr-2" />
                开始评价
              </Button>
            </Card>
          )}
        </TabsContent>

        {/* 评价结果 */}
        <TabsContent value="evaluation" className="space-y-4">
          {currentEvaluation ? (
            <div className="space-y-4">
              {/* 总体评价 */}
              <Card className="p-6 bg-card">
                <div className="flex items-center justify-between mb-4">
                  <h3 className="text-lg font-semibold">总体评价</h3>
                  <div className="flex items-center gap-3">
                    <div className="text-center">
                      <div
                        className="text-4xl font-bold"
                        style={{ color: getSoilGradeColor(currentEvaluation.overallGrade) }}
                      >
                        {currentEvaluation.overallScore}
                      </div>
                      <div className="text-sm text-muted-foreground">综合得分</div>
                    </div>
                    <div className="text-center">
                      <div
                        className="text-3xl font-bold"
                        style={{ color: getSoilGradeColor(currentEvaluation.overallGrade) }}
                      >
                        {currentEvaluation.overallGrade}级
                      </div>
                      <div className="text-sm text-muted-foreground">质量等级</div>
                    </div>
                  </div>
                </div>

                <div className="grid grid-cols-3 gap-4">
                  <Card className="p-4 bg-green-50 dark:bg-green-950">
                    <div className="flex items-center gap-2 mb-2">
                      <Leaf className="w-5 h-5 text-green-600 dark:text-green-400" />
                      <span className="font-medium">土壤类型</span>
                    </div>
                    <div className="text-lg text-green-600 dark:text-green-400">
                      {currentEvaluation.soilType}
                    </div>
                  </Card>
                  <Card className="p-4 bg-blue-50 dark:bg-blue-950">
                    <div className="flex items-center gap-2 mb-2">
                      <Droplets className="w-5 h-5 text-blue-600 dark:text-blue-400" />
                      <span className="font-medium">排水条件</span>
                    </div>
                    <div className="text-lg text-blue-600 dark:text-blue-400">
                      {currentEvaluation.drainage === 'excellent' && '优秀'}
                      {currentEvaluation.drainage === 'good' && '良好'}
                      {currentEvaluation.drainage === 'moderate' && '中等'}
                      {currentEvaluation.drainage === 'poor' && '较差'}
                    </div>
                  </Card>
                  <Card className="p-4 bg-purple-50 dark:bg-purple-950">
                    <div className="flex items-center gap-2 mb-2">
                      <Zap className="w-5 h-5 text-purple-600 dark:text-purple-400" />
                      <span className="font-medium">肥力水平</span>
                    </div>
                    <div className="text-lg text-purple-600 dark:text-purple-400">
                      {currentEvaluation.fertility === 'high' && '高'}
                      {currentEvaluation.fertility === 'medium' && '中'}
                      {currentEvaluation.fertility === 'low' && '低'}
                    </div>
                  </Card>
                </div>

                {/* 评价信息 */}
                <div className="grid grid-cols-2 gap-4 mt-6">
                  <div className="flex items-center gap-2 text-sm">
                    <Calendar className="w-4 h-4 text-muted-foreground" />
                    <span className="text-muted-foreground">评价日期：</span>
                    <span>{formatDate(currentEvaluation.date)}</span>
                  </div>
                  <div className="flex items-center gap-2 text-sm">
                    <User className="w-4 h-4 text-muted-foreground" />
                    <span className="text-muted-foreground">评价人员：</span>
                    <span>{currentEvaluation.evaluator}</span>
                  </div>
                  <div className="flex items-center gap-2 text-sm">
                    <MapPin className="w-4 h-4 text-muted-foreground" />
                    <span className="text-muted-foreground">地块位置：</span>
                    <span>{currentEvaluation.location}</span>
                  </div>
                  <div className="flex items-center gap-2 text-sm">
                    <Target className="w-4 h-4 text-muted-foreground" />
                    <span className="text-muted-foreground">下次评价：</span>
                    <span>{formatDate(currentEvaluation.nextEvaluationDate)}</span>
                  </div>
                </div>

                {currentEvaluation.evaluationNotes && (
                  <div className="mt-4 p-3 bg-muted rounded-lg">
                    <div className="text-sm text-muted-foreground mb-1">评价备注：</div>
                    <div className="text-sm">{currentEvaluation.evaluationNotes}</div>
                  </div>
                )}
              </Card>

              {/* 得分分布 */}
              <Card className="p-6 bg-card">
                <h3 className="mb-4">得分分布图</h3>
                <div className="space-y-3">
                  {currentEvaluation.indicators.map(indicator => (
                    <div key={indicator.id} className="space-y-2">
                      <div className="flex justify-between text-sm">
                        <span>{indicator.name}</span>
                        <span>{indicator.score}分</span>
                      </div>
                      <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                        <div
                          className="h-2 rounded-full"
                          style={{
                            width: `${indicator.score}%`,
                            backgroundColor: getIndicatorStatusColor(indicator.status)
                          }}
                        />
                      </div>
                    </div>
                  ))}
                </div>
              </Card>
            </div>
          ) : (
            <Card className="p-8 text-center bg-card">
              <Award className="w-16 h-16 mx-auto text-muted-foreground mb-4" />
              <h3 className="text-lg font-semibold mb-2">暂无评价结果</h3>
              <p className="text-muted-foreground mb-4">
                请先完成土壤质量分析以查看评价结果
              </p>
              <Button onClick={() => setShowForm(true)}>
                <Calculator className="w-4 h-4 mr-2" />
                开始评价
              </Button>
            </Card>
          )}
        </TabsContent>

        {/* 改良建议 */}
        <TabsContent value="recommendations" className="space-y-4">
          {currentEvaluation && currentEvaluation.recommendations.length > 0 ? (
            <div className="space-y-4">
              {currentEvaluation.recommendations.map((recommendation, index) => (
                <Card key={index} className="p-6 bg-card">
                  <div className="flex items-start justify-between mb-4">
                    <div className="flex items-center gap-3">
                      {recommendation.priority === 'high' && <AlertTriangle className="w-5 h-5 text-red-500" />}
                      {recommendation.priority === 'medium' && <AlertCircle className="w-5 h-5 text-yellow-500" />}
                      {recommendation.priority === 'low' && <Info className="w-5 h-5 text-blue-500" />}
                      <div>
                        <h4 className="font-semibold">{recommendation.title}</h4>
                        <p className="text-sm text-muted-foreground mt-1">{recommendation.description}</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <Badge variant={getPriorityBadgeVariant(recommendation.priority) as any}>
                        {recommendation.priority === 'high' && '高优先级'}
                        {recommendation.priority === 'medium' && '中优先级'}
                        {recommendation.priority === 'low' && '低优先级'}
                      </Badge>
                    </div>
                  </div>

                  {/* 行动项目 */}
                  <div className="mb-4">
                    <h5 className="font-medium mb-2">具体措施：</h5>
                    <ul className="space-y-1">
                      {recommendation.actionItems.map((item, itemIndex) => (
                        <li key={itemIndex} className="flex items-start gap-2 text-sm">
                          <CheckCircle className="w-4 h-4 text-green-500 mt-0.5 flex-shrink-0" />
                          <span>{item}</span>
                        </li>
                      ))}
                    </ul>
                  </div>

                  {/* 预期效果和成本 */}
                  <div className="grid grid-cols-3 gap-4">
                    <Card className="p-3 bg-green-50 dark:bg-green-950">
                      <div className="text-sm text-muted-foreground mb-1">预期改善</div>
                      <div className="font-bold text-green-600 dark:text-green-400">
                        +{recommendation.expectedImprovement}分
                      </div>
                    </Card>
                    <Card className="p-3 bg-blue-50 dark:bg-blue-950">
                      <div className="text-sm text-muted-foreground mb-1">实施周期</div>
                      <div className="font-bold text-blue-600 dark:text-blue-400">
                        {recommendation.timeframe}
                      </div>
                    </Card>
                    <Card className="p-3 bg-purple-50 dark:bg-purple-950">
                      <div className="text-sm text-muted-foreground mb-1">预估成本</div>
                      <div className="font-bold text-purple-600 dark:text-purple-400">
                        ¥{recommendation.estimatedCost}
                        {recommendation.costUnit === 'yuan_per_mu' && '/亩'}
                        {recommendation.costUnit === 'yuan_per_hectare' && '/公顷'}
                      </div>
                    </Card>
                  </div>
                </Card>
              ))}
            </div>
          ) : (
            <Card className="p-8 text-center bg-card">
              <ThumbsUp className="w-16 h-16 mx-auto text-muted-foreground mb-4" />
              <h3 className="text-lg font-semibold mb-2">土壤质量良好</h3>
              <p className="text-muted-foreground mb-4">
                当前土壤质量状况良好，暂无特殊改良建议
              </p>
              <Button variant="outline" onClick={() => setShowForm(true)}>
                <Calculator className="w-4 h-4 mr-2" />
                重新评价
              </Button>
            </Card>
          )}
        </TabsContent>

        {/* 历史记录 */}
        <TabsContent value="history" className="space-y-4">
          {historicalData.length > 0 ? (
            <div className="space-y-4">
              {/* 趋势分析 */}
              <Card className="p-6 bg-card">
                <h3 className="mb-4">质量趋势分析</h3>
                <div className="flex items-center gap-4">
                  <div className="flex-1">
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-sm text-muted-foreground">总体趋势</span>
                      <span className={`font-medium ${
                        historicalData[0].overallScore > historicalData[1]?.overallScore ? 'text-green-600' :
                        historicalData[0].overallScore < historicalData[1]?.overallScore ? 'text-red-600' :
                        'text-gray-600'
                      }`}>
                        {historicalData[0].overallScore > historicalData[1]?.overallScore && '↑ 上升趋势'}
                        {historicalData[0].overallScore < historicalData[1]?.overallScore && '↓ 下降趋势'}
                        {historicalData[0].overallScore === historicalData[1]?.overallScore && '→ 保持稳定'}
                      </span>
                    </div>
                    <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-3">
                      <div
                        className="h-3 rounded-full bg-gradient-to-r from-blue-500 to-green-500"
                        style={{ width: `${historicalData[0].overallScore}%` }}
                      />
                    </div>
                  </div>
                  <div className="text-center">
                    <div className="text-2xl font-bold text-green-600 dark:text-green-400">
                      {historicalData[0].overallScore}分
                    </div>
                    <div className="text-sm text-muted-foreground">最新评分</div>
                  </div>
                </div>
              </Card>

              {/* 历史记录列表 */}
              <div className="space-y-3">
                {historicalData.map((history, index) => (
                  <Card key={index} className="p-4 bg-card">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-4">
                        <div className="text-center">
                          <div
                            className="text-2xl font-bold"
                            style={{ color: getSoilGradeColor(history.evaluation.overallGrade) }}
                          >
                            {history.overallScore}
                          </div>
                          <div className="text-xs text-muted-foreground">得分</div>
                        </div>
                        <div>
                          <div className="font-medium">
                            {formatDate(history.date)} - {history.evaluation.overallGrade}级
                          </div>
                          <div className="text-sm text-muted-foreground">
                            评价人：{history.evaluation.evaluator}
                          </div>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        {index === 0 && (
                          <Badge variant="default">最新</Badge>
                        )}
                        <Button variant="outline" size="sm">
                          <Eye className="w-4 h-4 mr-1" />
                          查看
                        </Button>
                      </div>
                    </div>
                  </Card>
                ))}
              </div>
            </div>
          ) : (
            <Card className="p-8 text-center bg-card">
              <FileText className="w-16 h-16 mx-auto text-muted-foreground mb-4" />
              <h3 className="text-lg font-semibold mb-2">暂无历史记录</h3>
              <p className="text-muted-foreground mb-4">
                完成第一次土壤质量评价后将显示历史记录
              </p>
              <Button onClick={() => setShowForm(true)}>
                <Calculator className="w-4 h-4 mr-2" />
                开始评价
              </Button>
            </Card>
          )}
        </TabsContent>
      </Tabs>

      {/* 使用说明 */}
      <Card className="p-4 bg-blue-50 dark:bg-blue-950 border-blue-200 dark:border-blue-800">
        <div className="flex gap-2">
          <Info className="w-5 h-5 text-blue-600 dark:text-blue-400 flex-shrink-0" />
          <div className="text-sm text-blue-800 dark:text-blue-200">
            <p className="mb-2">土壤质量评价系统说明：</p>
            <ul className="space-y-1 text-xs">
              <li>• <strong>科学评价</strong>：基于13项关键指标进行综合评分，包括pH值、有机质、氮磷钾、微量元素等</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>
    </div>
  );
}