'use client';

import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Leaf, AlertTriangle, ThermometerSun, Cloud, Sun } from 'lucide-react';
import { CropRecommendationState, SuitabilityResult } from './cropRecommendReducer';

// 模拟作物知识库数据
const cropKnowledgeBase = [
  {
    id: 'wheat',
    cropName: '小麦',
    category: '粮食作物',
    description: '适应性强的主粮作物，对土壤要求较宽泛，耐寒性好，适合北方地区种植。',
    growthCycle: {
      days: 220,
      seasons: ['春季', '秋季']
    },
    soilRequirements: {
      ph: { optimal: [6.5, 7.5], acceptable: [6.0, 8.0] },
      organicMatter: { optimal: [25, 35], acceptable: [20, 40] },
      soilDepth: { optimal: [60, 100], acceptable: [40, 120] },
      nitrogen: { optimal: [1.5, 2.5], acceptable: [1.0, 3.0] },
      phosphorus: { optimal: [1.0, 2.0], acceptable: [0.6, 2.5] },
      potassium: { optimal: [15, 25], acceptable: [10, 30] },
      drainage: { optimal: [3, 5], acceptable: [2, 5] }
    },
    climateRequirements: {
      temperature: { optimal: [15, 22], acceptable: [10, 25] },
      rainfall: { optimal: [400, 600], acceptable: [300, 800] },
      sunlight: { optimal: [6, 8], acceptable: [5, 10] }
    },
    expectedYield: {
      high: [400, 500],
      medium: [300, 400],
      low: [200, 300]
    },
    riskFactors: [
      {
        id: 'wheat-rust',
        name: '锈病风险',
        condition: '湿度过高、温度适宜',
        severity: 'medium' as const,
        suggestion: '选择抗病品种，合理密植，及时防治'
      },
      {
        id: 'wheat-drought',
        name: '干旱风险',
        condition: '降雨量不足400mm',
        severity: 'high' as const,
        suggestion: '加强灌溉设施建设，选择抗旱品种'
      }
    ]
  },
  {
    id: 'corn',
    cropName: '玉米',
    category: '粮食作物',
    description: '高产作物，对温度要求较高，需水量大，适合水热条件良好的地区。',
    growthCycle: {
      days: 120,
      seasons: ['春季', '夏季']
    },
    soilRequirements: {
      ph: { optimal: [6.0, 7.0], acceptable: [5.5, 7.5] },
      organicMatter: { optimal: [30, 40], acceptable: [25, 45] },
      soilDepth: { optimal: [80, 120], acceptable: [60, 150] },
      nitrogen: { optimal: [2.0, 3.0], acceptable: [1.5, 3.5] },
      phosphorus: { optimal: [1.2, 2.5], acceptable: [0.8, 3.0] },
      potassium: { optimal: [20, 30], acceptable: [15, 35] },
      drainage: { optimal: [3, 5], acceptable: [2, 5] }
    },
    climateRequirements: {
      temperature: { optimal: [20, 28], acceptable: [15, 32] },
      rainfall: { optimal: [500, 800], acceptable: [400, 1000] },
      sunlight: { optimal: [7, 9], acceptable: [6, 10] }
    },
    expectedYield: {
      high: [600, 800],
      medium: [400, 600],
      low: [250, 400]
    },
    riskFactors: [
      {
        id: 'corn-borer',
        name: '玉米螟',
        condition: '温度适宜、湿度适中',
        severity: 'medium' as const,
        suggestion: '生物防治与化学防治结合，适时播种'
      },
      {
        id: 'corn-drought',
        name: '花期干旱',
        condition: '开花期降雨不足',
        severity: 'high' as const,
        suggestion: '保证花期灌溉，选择耐旱品种'
      }
    ]
  },
  {
    id: 'soybean',
    cropName: '大豆',
    category: '经济作物',
    description: '豆科作物，具有固氮能力，对土壤肥力要求较低，适合轮作种植。',
    growthCycle: {
      days: 100,
      seasons: ['春季', '夏季']
    },
    soilRequirements: {
      ph: { optimal: [6.0, 7.0], acceptable: [5.5, 7.5] },
      organicMatter: { optimal: [25, 35], acceptable: [20, 40] },
      soilDepth: { optimal: [50, 80], acceptable: [40, 100] },
      nitrogen: { optimal: [1.0, 2.0], acceptable: [0.5, 2.5] },
      phosphorus: { optimal: [0.8, 1.8], acceptable: [0.5, 2.5] },
      potassium: { optimal: [15, 25], acceptable: [10, 30] },
      drainage: { optimal: [3, 5], acceptable: [2, 5] }
    },
    climateRequirements: {
      temperature: { optimal: [18, 25], acceptable: [15, 28] },
      rainfall: { optimal: [450, 700], acceptable: [350, 900] },
      sunlight: { optimal: [6, 8], acceptable: [5, 9] }
    },
    expectedYield: {
      high: [250, 350],
      medium: [180, 250],
      low: [120, 180]
    },
    riskFactors: [
      {
        id: 'soybean-disease',
        name: '病害风险',
        condition: '高温高湿环境',
        severity: 'medium' as const,
        suggestion: '选择抗病品种，合理轮作，加强田间管理'
      }
    ]
  }
];

interface CropRecommendationsProps {
  state: CropRecommendationState;
  currentResult: SuitabilityResult;
}

export function CropRecommendations({ state, currentResult }: CropRecommendationsProps) {
  // 匹配作物推荐
  const matchCropsForField = (fieldFactors: any) => {
    return cropKnowledgeBase.map(crop => {
      let totalScore = 0;
      let factorCount = 0;
      const matchDetails: any[] = [];

      // 评估土壤因子匹配度
      Object.entries(crop.soilRequirements).forEach(([factor, requirements]: [string, any]) => {
        if (fieldFactors[factor]) {
          const value = fieldFactors[factor];
          const { optimal, acceptable } = requirements;

          let score = 0;
          let status = '偏离';

          if (value >= optimal[0] && value <= optimal[1]) {
            score = 100;
            status = '最佳';
          } else if (value >= acceptable[0] && value <= acceptable[1]) {
            const deviation = Math.min(
              Math.abs(value - optimal[0]),
              Math.abs(value - optimal[1])
            );
            const range = optimal[1] - optimal[0];
            score = Math.max(60, 100 - (deviation / range) * 40);
            status = '可接受';
          } else {
            score = Math.max(0, 60 - Math.min(
              Math.abs(value - acceptable[0]),
              Math.abs(value - acceptable[1])
            ) * 2);
          }

          totalScore += score;
          factorCount++;

          matchDetails.push({
            factor: factor === 'ph' ? 'pH值' :
                   factor === 'organicMatter' ? '有机质' :
                   factor === 'soilDepth' ? '土层厚度' :
                   factor === 'nitrogen' ? '全氮' :
                   factor === 'phosphorus' ? '全磷' :
                   factor === 'potassium' ? '全钾' : '排水性',
            value,
            score,
            status
          });
        }
      });

      // 评估气候因子（简化处理）
      if (fieldFactors.temperature) {
        const tempScore = fieldFactors.temperature >= 18 && fieldFactors.temperature <= 25 ? 90 : 70;
        totalScore += tempScore;
        factorCount++;
      }

      if (fieldFactors.rainfall) {
        const rainScore = fieldFactors.rainfall >= 500 && fieldFactors.rainfall <= 800 ? 90 : 70;
        totalScore += rainScore;
        factorCount++;
      }

      const matchScore = Math.round(totalScore / factorCount);

      // 确定适宜性等级
      let suitabilityLevel = '不推荐';
      if (matchScore >= 85) suitabilityLevel = '高度推荐';
      else if (matchScore >= 70) suitabilityLevel = '推荐';
      else if (matchScore >= 50) suitabilityLevel = '谨慎种植';

      // 根据适宜性等级选择产量区间
      let expectedYield = crop.expectedYield.low;
      if (suitabilityLevel === '高度推荐') expectedYield = crop.expectedYield.high;
      else if (suitabilityLevel === '推荐') expectedYield = crop.expectedYield.medium;

      // 识别适用风险
      const applicableRisks = crop.riskFactors.filter(risk => {
        if (risk.id.includes('drought') && fieldFactors.rainfall < 400) return true;
        if (risk.id.includes('rust') && fieldFactors.temperature >= 15 && fieldFactors.temperature <= 22) return true;
        return true; // 简化处理，默认显示所有风险
      });

      return {
        crop,
        matchScore,
        suitabilityLevel,
        matchDetails,
        applicableRisks,
        expectedYield
      };
    }).sort((a, b) => b.matchScore - a.matchScore);
  };

  // 获取地块因子数据
  const fieldFactors = {
    ph: currentResult.factors.find(f => f.id === 'ph')?.value || 0,
    organic: currentResult.factors.find(f => f.id === 'organic')?.value || 0,
    depth: currentResult.factors.find(f => f.id === 'depth')?.value || 0,
    nitrogen: currentResult.factors.find(f => f.id === 'nitrogen')?.value || 0,
    phosphorus: currentResult.factors.find(f => f.id === 'phosphorus')?.value || 0,
    potassium: currentResult.factors.find(f => f.id === 'potassium')?.value || 0,
    drainage: currentResult.factors.find(f => f.id === 'drainage')?.value || 0,
    temperature: 22, // 模拟年均温度
    rainfall: 800,   // 模拟年均降雨量
  };

  // 匹配推荐作物
  const recommendations = matchCropsForField(fieldFactors);

  return (
    <Card className="p-6">
      <div className="flex items-center justify-between mb-4">
        <h3 className="flex items-center gap-2">
          <Leaf className="w-5 h-5 text-green-600" />
          智能作物推荐清单
        </h3>
        <Badge variant="outline" className="text-xs">
          基于{cropKnowledgeBase.length}种作物知识库匹配
        </Badge>
      </div>

      <div className="space-y-4">
        {recommendations.map((recommendation, index) => {
          const { crop, matchScore, suitabilityLevel, matchDetails, applicableRisks, expectedYield } = recommendation;

          // 根据适宜性等级设置颜色
          const levelColor =
            suitabilityLevel === '高度推荐' ? { bg: 'bg-green-500', border: '#22c55e', text: 'text-green-600 dark:text-green-400' } :
            suitabilityLevel === '推荐' ? { bg: 'bg-blue-500', border: '#3b82f6', text: 'text-blue-600 dark:text-blue-400' } :
            suitabilityLevel === '谨慎种植' ? { bg: 'bg-yellow-500', border: '#eab308', text: 'text-yellow-600 dark:text-yellow-400' } :
            { bg: 'bg-gray-500', border: '#6b7280', text: 'text-gray-600 dark:text-gray-400' };

          // 只显示高度推荐和推荐的作物
          if (suitabilityLevel === '不推荐') return null;

          return (
            <Card key={index} className="p-5 border-l-4 hover:shadow-lg transition-shadow" style={{ borderLeftColor: levelColor.border }}>
              {/* 标题栏 */}
              <div className="flex items-start justify-between mb-4">
                <div className="flex items-center gap-3">
                  <div className={`p-2 rounded-lg bg-gradient-to-br from-green-50 to-green-100 dark:from-green-950 dark:to-green-900`}>
                    <Leaf className="w-6 h-6 text-green-600 dark:text-green-400" />
                  </div>
                  <div>
                    <div className="flex items-center gap-2">
                      <h4 className="mb-1">{crop.cropName}</h4>
                      <Badge variant="outline" className="text-xs">{crop.category}</Badge>
                    </div>
                    <div className="flex items-center gap-2">
                      <Badge className={`${levelColor.bg} text-white`}>
                        {suitabilityLevel}
                      </Badge>
                      <span className="text-xs text-muted-foreground">匹配度: {matchScore}分</span>
                    </div>
                  </div>
                </div>
                <div className="text-right">
                  <p className="text-xs text-muted-foreground mb-1">预期产量区间</p>
                  <p className={`text-lg font-medium ${levelColor.text}`}>
                    {expectedYield[0]}-{expectedYield[1]} kg/亩
                  </p>
                  <p className="text-xs text-muted-foreground mt-1">生长周期: {crop.growthCycle.days}天</p>
                </div>
              </div>

              {/* 作物描述 */}
              <p className="text-sm text-muted-foreground mb-3 p-2 bg-gray-50 dark:bg-gray-900 rounded">
                {crop.description}
              </p>

              {/* 土壤因子匹配详情 */}
              <div className="mb-3">
                <p className="text-xs text-muted-foreground mb-2">土壤因子匹配情况：</p>
                <div className="grid grid-cols-7 gap-2">
                  {matchDetails.map((detail, i) => (
                    <div key={i} className="p-2 bg-gray-50 dark:bg-gray-900 rounded text-center">
                      <p className="text-xs text-muted-foreground mb-1">{detail.factor}</p>
                      <p className="text-xs font-medium mb-1">{detail.value.toFixed(1)}</p>
                      {detail.status === '最佳' ? (
                        <Badge className="bg-green-500 text-white" style={{ fontSize: '9px', padding: '1px 4px' }}>
                          最佳
                        </Badge>
                      ) : detail.status === '可接受' ? (
                        <Badge className="bg-blue-500 text-white" style={{ fontSize: '9px', padding: '1px 4px' }}>
                          可接受
                        </Badge>
                      ) : (
                        <Badge variant="outline" className="text-red-500" style={{ fontSize: '9px', padding: '1px 4px' }}>
                          偏离
                        </Badge>
                      )}
                    </div>
                  ))}
                </div>
              </div>

              {/* 气候要求 */}
              <div className="grid grid-cols-3 gap-3 mb-3">
                <div className="p-2 bg-blue-50 dark:bg-blue-950 rounded-lg">
                  <p className="text-xs text-blue-600 dark:text-blue-400 mb-1 flex items-center gap-1">
                    <ThermometerSun className="w-3 h-3" />
                    温度要求
                  </p>
                  <p className="text-sm text-blue-900 dark:text-blue-100">
                    {crop.climateRequirements.temperature.optimal[0]}-{crop.climateRequirements.temperature.optimal[1]}°C
                  </p>
                </div>
                <div className="p-2 bg-cyan-50 dark:bg-cyan-950 rounded-lg">
                  <p className="text-xs text-cyan-600 dark:text-cyan-400 mb-1 flex items-center gap-1">
                    <Cloud className="w-3 h-3" />
                    降雨要求
                  </p>
                  <p className="text-sm text-cyan-900 dark:text-cyan-100">
                    {crop.climateRequirements.rainfall.optimal[0]}-{crop.climateRequirements.rainfall.optimal[1]}mm/年
                  </p>
                </div>
                <div className="p-2 bg-amber-50 dark:bg-amber-950 rounded-lg">
                  <p className="text-xs text-amber-600 dark:text-amber-400 mb-1 flex items-center gap-1">
                    <Sun className="w-3 h-3" />
                    光照要求
                  </p>
                  <p className="text-sm text-amber-900 dark:text-amber-100">
                    {crop.climateRequirements.sunlight.optimal[0]}-{crop.climateRequirements.sunlight.optimal[1]}小时/天
                  </p>
                </div>
              </div>

              {/* 风险提示 */}
              {applicableRisks.length > 0 && (
                <div className={`p-3 rounded-lg border ${
                  applicableRisks.some(r => r.severity === 'high')
                    ? 'bg-red-50 dark:bg-red-950 border-red-200 dark:border-red-800'
                    : 'bg-orange-50 dark:bg-orange-950 border-orange-200 dark:border-orange-800'
                }`}>
                  <p className="text-xs font-medium mb-2 flex items-center gap-1">
                    <AlertTriangle className={`w-4 h-4 ${
                      applicableRisks.some(r => r.severity === 'high')
                        ? 'text-red-600 dark:text-red-400'
                        : 'text-orange-600 dark:text-orange-400'
                    }`} />
                    <span className={applicableRisks.some(r => r.severity === 'high') ? 'text-red-900 dark:text-red-100' : 'text-orange-900 dark:text-orange-100'}>
                      风险提示与应对建议
                    </span>
                  </p>
                  <div className="space-y-2">
                    {applicableRisks.map((risk, i) => (
                      <div key={i} className="text-xs">
                        <div className="flex items-start gap-2">
                          <Badge
                            className={
                              risk.severity === 'high' ? 'bg-red-500 text-white' :
                              risk.severity === 'medium' ? 'bg-orange-500 text-white' :
                              'bg-yellow-500 text-white'
                            }
                            style={{ fontSize: '9px', padding: '2px 6px', marginTop: '2px' }}
                          >
                            {risk.severity === 'high' ? '高风险' : risk.severity === 'medium' ? '中风险' : '低风险'}
                          </Badge>
                          <div className="flex-1">
                            <p className={`font-medium mb-0.5 ${
                              applicableRisks.some(r => r.severity === 'high')
                                ? 'text-red-800 dark:text-red-200'
                                : 'text-orange-800 dark:text-orange-200'
                            }`}>
                              {risk.name}
                            </p>
                            <p className="text-muted-foreground mb-1">触发条件: {risk.condition}</p>
                            <p className={applicableRisks.some(r => r.severity === 'high') ? 'text-red-700 dark:text-red-300' : 'text-orange-700 dark:text-orange-300'}>
                              💡 {risk.suggestion}
                            </p>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* 适宜季节 */}
              <div className="mt-3 flex items-center gap-2 text-xs text-muted-foreground">
                <span>适宜种植季节:</span>
                {crop.growthCycle.seasons.map((season, i) => (
                  <Badge key={i} variant="outline" className="text-xs">
                    {season}
                  </Badge>
                ))}
              </div>
            </Card>
          );
        })}
      </div>
    </Card>
  );
}