'use client';

import { useReducer } from 'react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { BookOpen, Target } from 'lucide-react';
import {
  cropRecommendReducer,
  initialState,
  SuitabilityResult
} from './components/cropRecommendReducer';
import { FieldEnvironmentOverview } from './components/FieldEnvironmentOverview';
import { CropRecommendations } from './components/CropRecommendations';
import { KnowledgeBaseDialog } from './components/KnowledgeBaseDialog';

export default function CropPage() {
  const [state, dispatch] = useReducer(cropRecommendReducer, initialState);

  // 获取当前选中的地块结果
  const currentResult = state.evaluationResults.find(r => r.fieldId === state.selectedField) || state.evaluationResults[0];

  const handleFieldChange = (value: string) => {
    dispatch({ type: 'SET_SELECTED_FIELD', payload: value });
  };

  const handleToggleKnowledgeBase = () => {
    dispatch({ type: 'SET_SHOW_KNOWLEDGE_BASE', payload: !state.showKnowledgeBase });
  };

  const getGradeColor = (grade: string) => {
    switch (grade) {
      case '高度适宜': return 'bg-green-500';
      case '一般适宜': return 'bg-yellow-500';
      case '不适宜': return 'bg-red-500';
      default: return 'bg-gray-500';
    }
  };

  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={handleToggleKnowledgeBase}>
            <BookOpen className="w-4 h-4 mr-2" />
            作物知识库
          </Button>
        </div>
      </div>

      {/* 地块选择和适宜性概览 */}
      <div className="grid grid-cols-1 lg:grid-cols-4 gap-4">
        <div className="lg:col-span-1">
          <div className="space-y-4">
            <div className="p-4 bg-card rounded-lg border">
              <label className="text-xs text-muted-foreground mb-2 block">选择地块</label>
              <Select value={state.selectedField} onValueChange={handleFieldChange}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {state.evaluationResults.map((result) => (
                    <SelectItem key={result.fieldId} value={result.fieldId}>
                      {result.fieldName} - {result.grade} ({result.totalScore}分)
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* 适宜性评分卡片 */}
            <div className="p-4 bg-gradient-to-br from-green-50 to-green-100 dark:from-green-950 dark:to-green-900 rounded-lg border border-green-200 dark:border-green-800">
              <div className="text-center">
                <Target className="w-12 h-12 text-green-600 dark:text-green-400 mx-auto mb-3" />
                <p className="text-xs text-muted-foreground mb-2">适宜性评分</p>
                <p className="text-4xl font-bold text-green-600 dark:text-green-400 mb-2">{currentResult.totalScore}</p>
                <Badge className={`${getGradeColor(currentResult.grade)} text-white`}>
                  {currentResult.grade}
                </Badge>
              </div>
            </div>

            {/* 因子评分统计 */}
            <div className="p-4 bg-card rounded-lg border">
              <p className="text-sm font-medium mb-3">因子评分统计</p>
              <div className="space-y-2">
                <div className="flex justify-between text-xs">
                  <span className="text-muted-foreground">优秀因子</span>
                  <span className="text-green-600 font-medium">
                    {currentResult.factors.filter(f => f.score >= 80).length}
                  </span>
                </div>
                <div className="flex justify-between text-xs">
                  <span className="text-muted-foreground">待改善因子</span>
                  <span className="text-red-600 font-medium">
                    {currentResult.factors.filter(f => f.score < 70).length}
                  </span>
                </div>
                <div className="flex justify-between text-xs">
                  <span className="text-muted-foreground">评价时间</span>
                  <span className="text-muted-foreground">{currentResult.timestamp}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div className="lg:col-span-3">
          <FieldEnvironmentOverview currentResult={currentResult} />
        </div>
      </div>

      {/* 智能作物推荐 */}
      <CropRecommendations state={state} currentResult={currentResult} />

      {/* 知识库对话框 */}
      <KnowledgeBaseDialog
        showKnowledgeBase={state.showKnowledgeBase}
        onClose={handleToggleKnowledgeBase}
      />

      {/* 系统说明 */}
      <div className="p-5 bg-gradient-to-r from-green-50 to-blue-50 dark:from-green-950 dark:to-blue-950 rounded-lg border border-green-200 dark:border-green-800">
        <div className="flex items-start gap-3">
          <div className="p-2 bg-green-100 dark:bg-green-900 rounded-lg">
            <Target className="w-6 h-6 text-green-700 dark:text-green-300 flex-shrink-0" />
          </div>
          <div className="flex-1">
            <h4 className="text-green-900 dark:text-green-100 mb-3">作物-环境知识库匹配系统</h4>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 text-sm text-green-800 dark:text-green-200">
              <div>
                <p className="font-medium mb-2">🌾 知识库构成</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>作物种类</strong>: 多种主要农作物</li>
                  <li>• <strong>土壤参数</strong>: pH、有机质等7项指标</li>
                  <li>• <strong>气候参数</strong>: 温度、降雨、光照</li>
                  <li>• <strong>最佳范围</strong>: 每个因子的要求范围</li>
                </ul>
              </div>
              <div>
                <p className="font-medium mb-2">🎯 智能匹配流程</p>
                <ul className="space-y-1 text-xs">
                  <li>• <strong>参数对比</strong>: 地块值与要求对比</li>
                  <li>• <strong>评分计算</strong>: 最佳100分，可接受60分</li>
                  <li>• <strong>综合匹配度</strong>: 加权平均所有因子</li>
                  <li>• <strong>分级推荐</strong>: ≥85高度推荐，70-84推荐</li>
                </ul>
              </div>
              <div>
                <p className="font-medium 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>
                </ul>
              </div>
              <div>
                <p className="font-medium 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>
                </ul>
              </div>
            </div>

            <div className="mt-4 p-3 bg-white/60 dark:bg-black/20 rounded-lg border border-green-200 dark:border-green-800">
              <p className="text-xs text-green-900 dark:text-green-100">
                <strong>💡 系统优势：</strong>
                本系统整合了土壤科学、作物学、气象学等多学科知识，建立了完整的作物-环境适配知识库。
                通过科学的评分体系和智能匹配算法，为农业生产决策提供可靠的数据支持，帮助优化作物布局，
                提高土地利用率和经济效益，同时有效规避种植风险。
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}