'use client';

import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { MapPin, CheckCircle, Circle, Loader2, XCircle } from 'lucide-react';
import { SpatialAnalysisState, SpatialAnalysisAction } from './spatialAnalysisReducer';

interface LandBlockSelectorProps {
  state: SpatialAnalysisState;
  dispatch: React.Dispatch<SpatialAnalysisAction>;
  isDialog?: boolean;
}

export default function LandBlockSelector({ state, dispatch, isDialog = false }: LandBlockSelectorProps) {
  const handleSelectAll = () => {
    if (state.selectedBlocks.length === state.landBlocks.length) {
      dispatch({ type: 'SET_SELECTED_BLOCKS', payload: [] });
    } else {
      dispatch({ type: 'SET_SELECTED_BLOCKS', payload: state.landBlocks.map(b => b.id) });
    }
  };

  const getBlockScore = (blockId: string) => {
    const result = state.analysisResults.find(r => r.blockId === blockId);
    return result?.overallScore || null;
  };

  const getScoreColor = (score: number) => {
    if (score >= 80) return 'text-green-600';
    if (score >= 60) return 'text-yellow-600';
    return 'text-red-600';
  };

  const getScoreLabel = (score: number) => {
    if (score >= 80) return '优秀';
    if (score >= 60) return '良好';
    if (score >= 40) return '一般';
    return '较差';
  };

  if (isDialog) {
    // 对话框模式下的简化版本
    return (
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <h3 className="text-lg font-medium">选择分析地块</h3>
          <Button
            variant="outline"
            size="sm"
            onClick={handleSelectAll}
          >
            {state.selectedBlocks.length === state.landBlocks.length ? '取消全选' : '全选'}
          </Button>
        </div>

        <div className="space-y-2 max-h-96 overflow-y-auto">
          {state.landBlocks.map(block => {
            const isSelected = state.selectedBlocks.includes(block.id);
            const score = getBlockScore(block.id);

            return (
              <div
                key={block.id}
                className={`p-3 border rounded-lg cursor-pointer transition-colors ${
                  isSelected ? 'bg-blue-50 border-blue-200' : 'hover:bg-gray-50'
                }`}
                onClick={() => dispatch({ type: 'TOGGLE_BLOCK_SELECTION', payload: block.id })}
              >
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <Checkbox checked={isSelected} />
                    <div>
                      <p className="font-medium">{block.name}</p>
                      <p className="text-sm text-muted-foreground">
                        {block.area} 亩 · {block.soilType} · {block.irrigation}
                      </p>
                    </div>
                  </div>
                  {score && (
                    <Badge className={getScoreColor(score)}>
                      {score}分
                    </Badge>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  return (
    <Card className="p-6">
      <div className="flex items-center justify-between mb-6">
        <h3 className="text-lg font-medium">地块选择</h3>
        <div className="flex items-center gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={handleSelectAll}
          >
            {state.selectedBlocks.length === state.landBlocks.length ? '取消全选' : '全选'}
          </Button>
          <Badge variant="secondary">
            已选择 {state.selectedBlocks.length} / {state.landBlocks.length}
          </Badge>
        </div>
      </div>

      {/* 地块列表 */}
      <div className="space-y-3">
        {state.landBlocks.length === 0 ? (
          <div className="text-center py-8 text-muted-foreground">
            <MapPin className="w-12 h-12 mx-auto mb-3 opacity-50" />
            <p>暂无地块数据</p>
            <p className="text-sm mt-1">请先添加地块信息</p>
          </div>
        ) : (
          state.landBlocks.map(block => {
            const isSelected = state.selectedBlocks.includes(block.id);
            const score = getBlockScore(block.id);

            return (
              <div
                key={block.id}
                className={`p-4 border rounded-lg cursor-pointer transition-all ${
                  isSelected
                    ? 'bg-blue-50 dark:bg-blue-950 border-blue-200 dark:border-blue-800'
                    : 'hover:bg-gray-50 dark:hover:bg-gray-900 border-gray-200 dark:border-gray-700'
                }`}
                onClick={() => dispatch({ type: 'TOGGLE_BLOCK_SELECTION', payload: block.id })}
              >
                <div className="flex items-start justify-between">
                  <div className="flex items-start gap-3 flex-1">
                    <div className="pt-1">
                      {isSelected ? (
                        <CheckCircle className="w-5 h-5 text-blue-600" />
                      ) : (
                        <Circle className="w-5 h-5 text-gray-400" />
                      )}
                    </div>

                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        <h4 className="font-medium">{block.name}</h4>
                        {block.currentCrop && (
                          <Badge variant="outline" className="text-xs">
                            {block.currentCrop}
                          </Badge>
                        )}
                      </div>

                      {/* 地块基本信息 */}
                      <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">
                        <div className="flex items-center gap-1">
                          <span className="text-muted-foreground">面积:</span>
                          <span className="font-medium">{block.area} 亩</span>
                        </div>
                        <div className="flex items-center gap-1">
                          <span className="text-muted-foreground">土壤:</span>
                          <span className="font-medium">{block.soilType}</span>
                        </div>
                        <div className="flex items-center gap-1">
                          <span className="text-muted-foreground">灌溉:</span>
                          <span className="font-medium">{block.irrigation}</span>
                        </div>
                        <div className="flex items-center gap-1">
                          <span className="text-muted-foreground">海拔:</span>
                          <span className="font-medium">{block.elevation}m</span>
                        </div>
                      </div>

                      {/* 土壤指标 */}
                      <div className="mt-3 grid grid-cols-2 md:grid-cols-5 gap-3 text-xs">
                        <div>
                          <span className="text-muted-foreground">pH:</span>
                          <span className="ml-1 font-medium">{block.pH}</span>
                        </div>
                        <div>
                          <span className="text-muted-foreground">有机质:</span>
                          <span className="ml-1 font-medium">{block.organicMatter}%</span>
                        </div>
                        <div>
                          <span className="text-muted-foreground">氮:</span>
                          <span className="ml-1 font-medium">{block.nitrogen}</span>
                        </div>
                        <div>
                          <span className="text-muted-foreground">磷:</span>
                          <span className="ml-1 font-medium">{block.phosphorus}</span>
                        </div>
                        <div>
                          <span className="text-muted-foreground">钾:</span>
                          <span className="ml-1 font-medium">{block.potassium}</span>
                        </div>
                      </div>
                    </div>
                  </div>

                  {/* 分析状态和适宜性指数 */}
                  {(score || block.analysisStatus) && (
                    <div className="ml-4 text-center">
                      {block.analysisStatus === 'analyzing' && (
                        <div className="flex flex-col items-center">
                          <Loader2 className="w-6 h-6 text-blue-500 animate-spin" />
                          <div className="text-xs text-blue-500 mt-1">分析中</div>
                        </div>
                      )}
                      {block.analysisStatus === 'failed' && (
                        <div className="flex flex-col items-center">
                          <XCircle className="w-6 h-6 text-red-500" />
                          <div className="text-xs text-red-500 mt-1">分析失败</div>
                        </div>
                      )}
                      {block.analysisStatus === 'completed' && block.suitabilityIndex && (
                        <div>
                          <div className={`text-2xl font-bold ${getScoreColor(block.suitabilityIndex)}`}>
                            {block.suitabilityIndex}
                          </div>
                          <div className={`text-xs ${getScoreColor(block.suitabilityIndex)}`}>
                            适宜性指数
                          </div>
                          <Progress value={block.suitabilityIndex} className="w-16 h-2 mt-1" />
                          <div className="text-xs text-muted-foreground mt-1">
                            {block.lastAnalyzed}
                          </div>
                        </div>
                      )}
                      {score && !block.analysisStatus && (
                        <div>
                          <div className={`text-2xl font-bold ${getScoreColor(score)}`}>
                            {score}
                          </div>
                          <div className={`text-xs ${getScoreColor(score)}`}>
                            {getScoreLabel(score)}
                          </div>
                          <Progress value={score} className="w-16 h-2 mt-1" />
                        </div>
                      )}
                    </div>
                  )}
                </div>
              </div>
            );
          })
        )}
      </div>

      {/* 选中地块统计 */}
      {state.selectedBlocks.length > 0 && (
        <div className="mt-6 p-4 bg-green-50 dark:bg-green-950 border border-green-200 dark:border-green-800 rounded-lg">
          <h4 className="font-medium text-green-900 dark:text-green-100 mb-2">选中地块统计</h4>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm text-green-800 dark:text-green-200">
            <div>
              <span className="text-muted-foreground text-green-700 dark:text-green-300">地块数量:</span>
              <span className="ml-1 font-medium">{state.selectedBlocks.length} 个</span>
            </div>
            <div>
              <span className="text-muted-foreground text-green-700 dark:text-green-300">总面积:</span>
              <span className="ml-1 font-medium">
                {state.landBlocks
                  .filter(b => state.selectedBlocks.includes(b.id))
                  .reduce((sum, b) => sum + b.area, 0)
                  .toFixed(1)} 亩
              </span>
            </div>
            <div>
              <span className="text-muted-foreground text-green-700 dark:text-green-300">平均得分:</span>
              <span className="ml-1 font-medium">
                {state.analysisResults.length > 0
                  ? Math.round(
                      state.analysisResults
                        .filter(r => state.selectedBlocks.includes(r.blockId))
                        .reduce((sum, r) => sum + r.overallScore, 0) /
                      state.analysisResults.filter(r => state.selectedBlocks.includes(r.blockId)).length
                    )
                  : '--'
                } 分
              </span>
            </div>
            <div>
              <span className="text-muted-foreground text-green-700 dark:text-green-300">土壤类型:</span>
              <span className="ml-1 font-medium">
                {[...new Set(
                  state.landBlocks
                    .filter(b => state.selectedBlocks.includes(b.id))
                    .map(b => b.soilType)
                )].join(', ')}
              </span>
            </div>
          </div>
        </div>
      )}
    </Card>
  );
}